Martha
Martha

Reputation: 111

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

Upvotes: 6

Views: 576

Answers (3)

Saravana
Saravana

Reputation: 12817

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())));

Upvotes: 10

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

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;
}

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56413

Given you have a List<List<String>> as the source, you can use forEach + computeIfAbsent:

Map<String, Set<String>> map = new HashMap<>();
list.forEach(l -> map.computeIfAbsent(l.get(0), k -> new HashSet<>()).add(l.get(1)));

Upvotes: 0

Related Questions