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?
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.
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.
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.
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);
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>
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);
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