这是我的数据集。
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的输出:{running = 13,swimming = 22,shuttle = 12,throwball = 4,basketball = 13,chess = 2,cricket = 23,boxing = 10,football = 26,tennis = 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的输出:{running = 2,swimming = 2,shuttle = 1,throwball = 1,basketball = 3,chess = 1,cricket = 4,boxing = 1,football = 5,tennis = 2}
1.it没有排序并给出相同的结果。任何想法?
我正在编写单独的代码进行排序。是否可以在collect8中自行完成?
答案 0 :(得分:-1)
对于第一个问题,Collectors.toMap()
目前创建的HashMap
没有排序,因此排序Stream
对最终Map
没有影响。如果您改为创建LinkedHashMap
,则会保留广告订单。
Map<String, Integer> collect9 =
collect8.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue()).
collect(Collectors.toMap(e->e.getKey(), e->e.getValue(),(v1,v2)->v2,LinkedHashMap::new));
至于在单个管道中进行分组和排序,我不知道如何实现这一点。如果完成排序是通过Map
的密钥完成的,那么您可以通过在第一个TreeMap
Stream
中生成collect
来轻松实现排序,但是因为您需要要按值排序,我无法在单个Stream
管道中看到这样做的方法。