简体   繁体   中英

Java: List<List<String>> list = new ArrayList<>();

How I can group all lists in list which contains same exact value.

List<List<String>> list = new ArrayList<>();

This list contains list1 list2 list3 and etc.... I want to find if list1.get(0) is the same as list2.get(0) if no check with list3.get(0) and etc... Later I need to group lists if I find the same values in each. For example if true add list1 and list3 and others which were found to

  List<List<String>> list2 = new ArrayList<>();

Now check with list2.get(0) if equal to others if yes group them and add them to anoter:

   List<List<String>> list3 = new ArrayList<>();

What I achieved so far:

    private static void findEqualLists(List<List<String>> list) {

    int i = 0;
    for (List<String> list1 : list) {
        if (!Collections.disjoint(list1, list.get(i))) {
            System.out.println(list1.get(0)+list.get(i).get(0));
        }else{
            System.out.println(list1.get(0)+list.get(i).get(0));
        }
        i++;
    }
}

Value exmaple:

list = {{2017-02,jhon,car},{2017-03,maria,car},{2017-03, boy, car}, {2017-01,arya, car}, {2017-02, girl, car}}

Output:

Group1:
2017-03,maria,car
2017-03, boy, car

Group2:
2017-02,jhon,car
2017-02, girl, car

Group3
2017-01,arya, car

You want Collectors.groupingBy :

private static Map<String, List<List<String>>>
            findEqualLists(List<List<String>> list) {

    return list.stream().collect(Collectors.groupingBy(l -> l.get(0)));
}

The returned Map will use l.get(0) as a unique key, with each corresponding value being a List of only those Lists whose first element matches that key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM