Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use streams to find pairs of elements from two lists or array multiplication

Tags:

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] + "}");     }); } 
like image 983
Ankur Singh Avatar asked Feb 14 '17 07:02

Ankur Singh


People also ask

How do you find all possible pairs in an array?

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.

Can we apply streams on Array?

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.

How do you find common elements in multiple lists?

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.

How should we in a stream to calculate sum of elements?

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.


1 Answers

Use flatMap() method instead of map(), it will combine the streams into one. Refer : Difference Between map() and flatMap() and flatMap() example

like image 59
Rohit Gulati Avatar answered Sep 22 '22 17:09

Rohit Gulati