I need to group the ABC List, while doing this I also wanted to split the value. Input:
List<ABC> list = new ArrayList<>();
ABC A1 = new ABC();
A1.setName("OO");
A1.setVal("OO111,OO222,OO333"); // split this while grouping
list.add(A1);
ABC A2 = new ABC();
A2.setName("OO");
A2.setVal("OO1");
list.add(A2);
ABC A3 = new ABC();
A3.setName("YY");
A3.setVal("1333,11444");
list.add(A3);
Output:
```java
Map<String, List<String>> postsPerType;
//Group by Name: ex: OO & YY. Split the Value by "," and add it to list
Key: 00 Values: List: "OO111","OO222","OO333","OO1"
Key: YY Values: List: "1333","11444"
Please suggest, thanks.
If you're on Java 9+, you can use Collectors.flatMapping() as groupingBy's downstream:
list.stream().collect(Collectors.groupingBy(ABC::getName,
Collectors.flatMapping(a -> Arrays.stream(a.getVal().split(",")),
Collectors.toList())));
That should produce exactly your desired result.
I think you can chain a reducing collector to the groupingBy collector to get what you need:
Map<String, List<String>> postsPerType =
list.stream()
.collect(Collectors.groupingBy(ABC::getName,
Collectors.reducing(new ArrayList<String>(),
a -> Arrays.asList(a.getVal().split(",")),
(l1,l2)-> {
List<String> l = new ArrayList<>();
l.addAll(l1);
l.addAll (l2);
return l;
})));
This produces the following Map:
{YY=[1333, 11444], OO=[OO111, OO222, OO333, OO1]}
Another way is using groupingBy and collectingAndThen collectors.
list.stream()
.collect(Collectors.groupingBy(
ABC::getName,
Collectors.collectingAndThen(
Collectors.mapping(ABC::getVal, toList()),
strings -> strings.stream()
.flatMap(s -> Arrays.stream(s.split(",")))
.collect(toList()))
));