【发布时间】:2018-05-18 14:49:50
【问题描述】:
这是我的数据集。
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")));
}
}
从数据集中,我发现有多少学生基于爱好并以 asc/desc 顺序显示值。例如:板球、4 和游泳:2 等等。
这是按啤酒花分组的代码。
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))));
collect8 的输出:{跑步=13,游泳=22,穿梭=12,投掷球=4,篮球=13,国际象棋=2,板球=23,拳击=10,足球=26,网球=21}
之后我按值进行 asc 排序。
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);
collect9 的输出:{跑步=2,游泳=2,穿梭=1,投掷=1,篮球=3,国际象棋=1,板球=4,拳击=1,足球=5,网球=2}
1.它没有排序并给出相同的结果。知道吗?
2. 我正在编写单独的代码进行排序。可以在collect8本身做吗?
【问题讨论】:
标签: java java-8 java-stream