Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 : groupby with Comparator

Tags:

java

java-8

I have a list of int for example (1,2,4,6,7,8). I want to know if there is away in Java 8 to create a list of lists.

If

(x,y)->x+1=y 

it should be in the same list.

In this example the output should be:

(1,2), (4), (6,7,8)

I can write in this way :

public static List<List<int>> group(List<int> list, GroupFunctionByOrder groupFunction) {

    List<List<int>> result = new ArrayList<>();

    for (int l : list) {

        boolean groupFound = false;
        for (List<int> group : result) {
            if (groupFunction.sameGroup(l, group.get(group.size()-1))) {
                group.add(l);
                groupFound = true;
                break;
            }
        }

        if (! groupFound) {
            List<int> newGroup =  new ArrayList<>();
            newGroup.add(l);
            result.add(newGroup);
        }
    }

    return result;
}

public class GroupFunctionByOrder {
    public boolean sameGroup(int l1, int  l2){
        return l1+1 == l2;
    }
}
like image 632
Tzlil Goldberg Avatar asked Mar 07 '23 02:03

Tzlil Goldberg


1 Answers

You can do this with the StreamEx library:

List<List<Integer>> grouped = StreamEx.of(1,2,4,6,7,8)
        .groupRuns((x, y) -> x + 1 == y)
        .toList();
like image 164
shmosel Avatar answered Mar 16 '23 08:03

shmosel