简体   繁体   中英

Comparing two Integer list using java8 filter

I have a problem as follows. There are two Integer list a and b with equal size. Now I want to compare both list value at same index. My function returns list with 2 values. First value is count of value greater in list a. Second value is count of value greater in list b. If both has same value than no increment in count.

can I get some idea how it can be achieved in java8 using stream/filter/predicates

I had retrun the method in older java version.

    static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) {
        List<Integer> list = new ArrayList<Integer>();
        int asize = 0;
        int bsize = 0;
        for (int i = 0; i <b.size();i++) {
            if(a.get(i) > b.get(i)) {
                asize++;
            }else if(a.get(i) < b.get(i)) {
                bsize++;
            }
        }
        list.add(asize);
        list.add(bsize);
        return list;
    }

eg1. Input: a =5 6 7 b = 3 6 10 Output: 1 1 eg 2. Input: a = 17 28 30 b = 99 16 8 Output: 2 1

First filter out all the equal values. Then create a map with a boolean key, representing whether the given value in a is less than or greater than the corresponding value in b . Finally use the counting collector to get the count for each category. Here's how it looks.

Collection<Long> gtAndLtCount = IntStream.range(0, a.size())
    .filter(i -> a.get(i) != b.get(i)).boxed()
    .collect(Collectors.partitioningBy(i -> a.get(i) < b.get(i), Collectors.counting()))
    .values();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM