Hi I have a String ArrayList of ArrayList. A sample is shown below:
[[765,servus, burdnare],
[764,asinj, ferrantis],
[764,asinj, ferrantis],
[764,asinj, ferrantis],
[762,asinj, ferrantis],
[756,peciam terre, cisterne],
[756,peciam terre, cortile],
[756,peciam terre, domo],
[756,asinj, ferrantis]]
Is it possible to get a list of unique values at index 1 for each value of index 0...The result I am expecting is:
765 - [servus]
764 - [asinj]
762 - [asinj]
756 - [peciam terre, asinj]
I was trying a series of if statements however did not work
You can group by index-0 element and collect index-1 elements in a Set
to get unique
List<List<String>> listOfList = ...//
Map<String, Set<String>> collect = listOfList.stream()
.filter(l -> l.size() >= 2)
.collect(Collectors.groupingBy(l -> l.get(0), Collectors.mapping(l -> l.get(1), Collectors.toSet())));
One of possibel variant. Just iterate over the given list and build Map
with required key
and Set
as value to ignore duplicates.
public static Map<String, Set<String>> group(List<List<String>> listOfList) {
Map<String, Set<String>> map = new LinkedHashMap<>();
listOfList.forEach(item -> map.compute(item.get(0), (id, names) -> {
(names = Optional.ofNullable(names).orElseGet(HashSet::new)).add(item.get(1));
return names;
}));
return map;
}
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