Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 streams how to find min difference between elements of 2 lists

I'm totally new to Streams of Java 8 and currently trying to solve this task, I have two lists as follow:

List<Integer> list1 = Arrays.asList(5, 11,17,123);
List<Integer> list2 = Arrays.asList(124,14,80);

I want to find the absolute min difference existing between all the elements out of these lists.

The expected result: 1(124-123=1)

It's not a problem to implement it with Java 7, but how i can achieve it with Streams of Java8? How i can iterate forEach element from List1 and also forEach from List2 and to keep the min value?

like image 719
nikabu Avatar asked Apr 04 '18 12:04

nikabu


1 Answers

Try this one

public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(5, 11,17,123); 
        List<Integer> list2 = Arrays.asList(124,14,80);
        OptionalInt min = list1.stream()
                          .flatMap(n -> list2.stream()
                          .map(r -> n-r > 0? n-r: r-n))
                          .mapToInt(t -> t).min();
        System.out.println(min.getAsInt());
    }

Edit(Holger suggestion)

 OptionalLong min = list1.stream()
.flatMapToLong(n -> list2.stream()
.mapToLong(r -> Math.abs(r-(long)n))).min();
like image 55
SEY_91 Avatar answered Jan 02 '23 19:01

SEY_91