Comparing two Integer list using java8 filter

Yogi :

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;
    }

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

Ravindra Ranwala :

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();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125846&siteId=1