I have an int list, for example (1,2,4,6,7,8). I want to know if there is in Java 8 to create a list of lists.
If
(x,y)->x+1=y
he must be on the same list.
In this example, the output should be:
(1,2), (4), (6,7,8)
I can write as follows:
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;
}
}
source
share