Here is my data set.
public class StudentData {
public static List<Student> getData() {
//student id,name,std, and hobbies
return Arrays.asList(new Student(1, "a1", 1, Arrays.asList("cricket", "football", "basketball")),
new Student(2, "a2", 1, Arrays.asList("chess", "football")),
new Student(3, "a3", 2, Arrays.asList("running")),
new Student(4, "a4", 2, Arrays.asList("throwball", "football")),
new Student(5, "a5", 3, Arrays.asList("cricket", "basketball")),
new Student(6, "a6", 4, Arrays.asList("cricket")), new Student(7, "a7", 5, Arrays.asList("basketball")),
new Student(8, "a8", 6, Arrays.asList("football")),
new Student(9, "a9", 8, Arrays.asList("tennis", "swimming")),
new Student(10, "a10", 8, Arrays.asList("boxing", "running")),
new Student(11, "a11", 9, Arrays.asList("cricket", "football")),
new Student(12, "a12", 11, Arrays.asList("tennis", "shuttle")),
new Student(13, "a13", 12, Arrays.asList("swimming")));
}
}
From data set , i am finding , how many student based on hobbies and display the value in asc/desc order. For example : cricket ,4 and swimming: 2 and so on.
here is the code for group by hoppies .
Map<String, Integer> collect8 = data.stream()
.flatMap(x -> x.getHobbies().stream().map(y -> new SimpleEntry<>(y, x)))
.collect(Collectors.groupingBy(Entry::getKey, Collectors.mapping(entry -> entry.getValue().getId(),
Collectors.reducing(0, (a, b) -> a + b))));
output of collect8 :{running=13, swimming=22, shuttle=12, throwball=4, basketball=13, chess=2, cricket=23, boxing=10, football=26, tennis=21}
After that i am doing asc sorting by value .
Map<String, Integer> collect9 =
collect8.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue()).
collect(Collectors.toMap(e->e.getKey(), e->e.getValue()));
System.out.println(collect9);
output of collect9 : {running=2, swimming=2, shuttle=1, throwball=1, basketball=3, chess=1, cricket=4, boxing=1, football=5, tennis=2}
1.it is not sorted and giving the same result.any idea?
2. i am writing separate code for sorting. is it possble to do in collect8 itself?