Java 8:groupby with Comparator

Tzl*_*erg 4 java java-8

我有一个int列表例如(1,2,4,6,7,8).我想知道Java 8中是否存在创建列表列表的问题.

如果

(x,y)->x+1=y 
Run Code Online (Sandbox Code Playgroud)

它应该在同一个列表中.

在此示例中,输出应为:

(1,2), (4), (6,7,8)
Run Code Online (Sandbox Code Playgroud)

我可以这样写:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

shm*_*sel 5

您可以使用StreamEx库执行此操作:

List<List<Integer>> grouped = StreamEx.of(1,2,4,6,7,8)
        .groupRuns((x, y) -> x + 1 == y)
        .toList();
Run Code Online (Sandbox Code Playgroud)

  • 应该提到这需要对流进行排序.问题并不表明样本数据是给出还是仅仅是巧合... (3认同)