预期效果: 按照年纪倒序并分组
实际结果:返回的数据是杂乱无章,并没有按照年纪倒序
示例代码如下:
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
- @author miao
*/
public class GroupBySort {
public static void main(String[] args) {
//构造数据
List students = Stream.of(
new Student("a", 15),
new Student("b", 13),
new Student("c", 11),
new Student("d", 18),
new Student("e", 20)
).collect(Collectors.toList());
//按照年纪倒序并分组
Map> studentMap = students.stream()
.sorted(Comparator.comparing(Student::getAge).reversed())
.collect(Collectors.groupingBy(Student::getAge));
System.out.println(studentMap);
}
}
class Student {
private String name;
private Integer age;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}