I have two lists of numbers and I'd like to find all possible pairs of numbers. For example, given the lists [1, 2, 3]
and [3, 4]
the result should be:
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
I know I can do this using a for loop but is there any more concise way to do it using Java 8 streams?
I tried the following, but I'm missing something as I'm getting List<Stream<int[]>>
instead of List<int[]>
.
public static void main(String[] args) { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(3, 4); List<int[]> pairs = list1.stream() .map(i -> list2.stream() .map(j -> new int[]{i, j})) .collect(Collectors.toList()); pairs.forEach(i -> { System.out.println("{" + i[0] + "," + i[1] + "}"); }); }
In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1. Below is the step by step approach: Traverse the array and select an element in each traversal.
stream() method only works for primitive arrays of int[], long[], and double[] type, and returns IntStream, LongStream and DoubleStream respectively. For other primitive types, Arrays. stream() won't work.
You can transform the lists to sets, and then use Set. retainAll method for intersection between the different sets. Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.
sum() The Stream API provides us with the mapToInt() intermediate operation, which converts our stream to an IntStream object. This method takes a mapper as a parameter, which it uses to do the conversion, then we can call the sum() method to calculate the sum of the stream's elements.
Use flatMap() method instead of map(), it will combine the streams into one. Refer : Difference Between map() and flatMap() and flatMap() example
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