Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert two dimension object Set/ArrayList into one Flat Set/List using java 8

I'm new in java 8 , I have Set of Set for example:

Set<Set<String>> aa = new HashSet<>();
Set<String> w1 = new HashSet<>();

w1.add("1111");
w1.add("2222");
w1.add("3333");

Set<String> w2 = new HashSet<>();
w2.add("4444");
w2.add("5555");
w2.add("6666");

Set<String> w3 = new HashSet<>();
w3.add("77777");
w3.add("88888");
w3.add("99999");

aa.add(w1);
aa.add(w2);
aa.add(w3);

EXPECTED RESULT: FLAT SET...something like:

But it doesn't work!

// HERE I WANT To Convert into FLAT Set 
// with the best PERFORMANCE !!
Set<String> flatSet = aa.stream().flatMap(a -> setOfSet.stream().flatMap(ins->ins.stream().collect(Collectors.toSet())).collect(Collectors.toSet()));

Any ideas?

like image 206
VitalyT Avatar asked Apr 18 '16 06:04

VitalyT


People also ask

How do you flatten a 2D list in Java?

Get the Lists in the form of 2D list. Create an empty list to collect the flattened elements. With the help of forEach loop, convert each elements of the list into stream and add it to the list. Now convert this list into stream using stream() method.

How do I flatten a list in Java 8?

The standard solution is to use the Stream. flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.

How do you turn an ArrayList into a set?

There are four ways to convert ArrayList to HashSet :Using constructor. Using add() method by iterating over each element and adding it into the HashSet. Using addAll() method that adds all the elements in one go into the HashSet. Using stream.

How can I turn a list of lists into a list in Java 8?

Here is the simple, concise code to perform the task. // listOfLists is a List<List<Object>>. List<Object> result = new ArrayList<>(); listOfLists. forEach(result::addAll);


2 Answers

You only need to call flatMap once :

Set<String> flatSet = aa.stream() // returns a Stream<Set<String>>
                        .flatMap(a -> a.stream()) // flattens the Stream to a 
                                                  // Stream<String>
                        .collect(Collectors.toSet()); // collect to a Set<String>
like image 125
Eran Avatar answered Oct 13 '22 23:10

Eran


As an alternative to @Eran's correct answer, you can use the 3-argument collect:

Set<String> flatSet = aa.stream().collect(HashSet::new, Set::addAll, Set::addAll);
like image 35
Misha Avatar answered Oct 14 '22 00:10

Misha