Java8:groupby与Comparator
例如,我有一个int列表(1,2,4,6,7,8)。 我想知道Java 8中是否有创建列表的方法
如果
(x,y)->x+1=y
它应该在同一个列表中
在本例中,输出应为:
(1,2), (4), (6,7,8)
我可以这样写:
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;
}
}
共 (0) 个答案