Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping in arrayList of arrayList

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

like image 510
Martha Avatar asked Dec 28 '18 20:12

Martha


2 Answers

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())));
like image 56
Saravana Avatar answered Oct 12 '22 11:10

Saravana


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;
}
like image 1
oleg.cherednik Avatar answered Oct 12 '22 12:10

oleg.cherednik