I have a list of items as below
List<SomeModel> smList = new ArrayList<>(); smList.add(new SomeModel(1L,6.0f));//id = 1L and capacity = 6.0f smList.add(new SomeModel(2L,7.0f)); smList.add(new SomeModel(3L,7.0f)); smList.add(new SomeModel(4L,7.0f));
Now I am converting this list into
Map<Float, Set<Long>> complexList = new HashMap<>(); complexList = smList.stream().collect(Collectors.groupingBy(SomeModel::getCapacity, Collectors.mapping(SomeModel::getId, Collectors.toSet())));
here complexList gives output as
7.0=[2, 3, 4] 6.0=[1]
Now I need to count number of values for each “capacity” giving output as
7.0=3 6.0=1
I tried
Map<Float, Long> complexCount = complexList.entrySet().stream(). collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.counting()))); complexCount.forEach((k,v)->System.out.println(k+"="+v));
and it outputs
6.0=1 7.0=1
I must be mistaking in understanding streams or not be using right methods. Can anyone suggest an approach or a solution? Reference link to streams will also be helpful.
Advertisement
Answer
if all you want to do is print each key of the map along with the size of the corresponding value, then there is no need to stream again as it causes unnecessary overhead. simply iterate overly the complexList
and print it like so:
complexList.forEach((k,v)->System.out.println(k+"="+v.size()));
or if you really want a map then one could also do:
Map<Float, Integer> accumulator = new HashMap<>(); complexList.forEach((k,v)->accumulator.put(k, v.size()));