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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With