我有一个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)
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)
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |