Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 518
Yogi Avatar asked Nov 27 '25 18:11

Yogi


1 Answers

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();
like image 186
Ravindra Ranwala Avatar answered Dec 02 '25 06:12

Ravindra Ranwala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!