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;
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With