yam*_*ato 4 java java-8 java-stream
例如,我有一个班级 Student
public class Student{
private String name;
private int age;
public int getAge(){
return this.age;
}
}
Run Code Online (Sandbox Code Playgroud)
一节课School:
public class School{
private Map<String,Student> students=new TreeMap<>();
//stroe the index of students in the school by key is their names.
public SortedMap<Integer,Long> countingByAge(){
return this.students.entrySet().stream().map(s->s.getValue())
.collect(groupingBy((Student s)->s.getAge(),counting()));
}
}
Run Code Online (Sandbox Code Playgroud)
countingByAge方法要求返回a SortedMap<Integer,Long >,关键是学生的年龄,值是每个不同年龄的学生数,即我需要计算每个年龄的学生数.
我已经几乎完成了方法,但我不知道如何转换Map<Integer,Long>到SortedMap<Integer,Long>无(SortedMap<Integer,Long>)铸造.
您可以使用groupingBy(classifier, mapFactory, downstream) 和mapFactory通地图供应商实施的返回情况下SortedMap像TreeMap::new
public SortedMap<Integer, Long> countingByAge(){
return students.entrySet()
.stream()
.map(Map.Entry::getValue)
.collect(groupingBy(Student::getAge, TreeMap::new, counting()));
}
Run Code Online (Sandbox Code Playgroud)
map.entrySet()
.stream()
.map(Map.Entry::getValue)
Run Code Online (Sandbox Code Playgroud)
同
map.values()
.stream()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1442 次 |
| 最近记录: |