I am trying to create a map using groupingBy(...)
function in lambda. Now the problem I am facing is I am unable to convert list to map for particular condition
Code:
List<Integer> list = IntStream
.range(0,120)
.mapToObj(Integer::new)
.collect(Collectors.toList());
Expected functionality:
I need to collect a map whose key is key value like keys from 0 to 120 and values will increase like
[]
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.
.
.
//so on upto 120
Map<Integer, List<Integer>> myMapOne = new HashMap<>();
for (Integer inteter : list) {
myMapOne.put(inteter, list.subList(0, list.indexOf(inteter)));
}
What I am trying (idea):
Map<Integer, Integer> myMap = list
.stream()
.collect(Collectors.groupingBy(Integer::new, list.subList(0, Integer::new)));
Error: not able to convert to List inside groupingBy()
or not sure if I am missing something
How to solve this? Any help is welcome
Edit:
do I need to use method reference here?
Below is method
public static List<Integer> getList(Integer index, List<Integer> list) {
return list.subList(0, list.indexOf(index));
}