【发布时间】:2019-08-28 05:47:59
【问题描述】:
在空格中使用 lambda 表达式编写逻辑相同的代码时遇到问题。 如何缩写 //Question Code ~ Question Code // 一句话用 lambda 表达式阻塞??
public class Student {
public enum Sex{MALE,FEMALE}
public enum City{Seoul,Busan}
private String name;
private int score;
private Sex sex;
private City city;
Student(String name,int score,Sex sex,City city){
this.name=name;
this.score=score;
this.sex=sex;
this.city=city;
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getScore() {return score;}
public void setScore(int score) {this.score = score;}
public Sex getSex() {return sex;}
public void setSex(Sex sex) {this.sex = sex;}
public City getCity() {return city;}
public void setCity(City city) {this.city = city;}
}
public class GroupingExample {
public static void main(String[] args) {
List<Student> totalList= new ArrayList<>();
totalList.add(new Student("Nafla",100,Student.Sex.MALE,Student.City.Seoul));
totalList.add(new Student("Loopy",99,Student.Sex.MALE,Student.City.Seoul));
totalList.add(new Student("Paloalto",98,Student.Sex.MALE,Student.City.Busan));
totalList.add(new Student("KidMilli",97,Student.Sex.MALE,Student.City.Busan));
totalList.add(new Student("YunWhey",90,Student.Sex.FEMALE,Student.City.Seoul));
totalList.add(new Student("JackyWai",100,Student.Sex.FEMALE,Student.City.Seoul));
//Question Code
Stream<Student> totalStream= totalList.stream();
Function<Student,Student.Sex> classifier = Student :: getSex;
Collector<Student,?,Map<Student.Sex,List<Student>>> collector = Collectors.groupingBy(classifier);
Map<Student.Sex,List<Student>> mapBySex = totalStream.collect(collector);
//Question Code
//Write the logically same code at underline using Lambda Expression.
Map<Student.Sex,List<Student>> mapBySexWithLambda = "Blank space"
【问题讨论】:
-
这就像用分配给它的值替换每个变量一样简单,除非您对简化感到满意。
Map<Student.Sex, List<Student>> mapBySexWithLambda = totalList.stream().collect(Collectors.groupingBy(student -> student.getSex()))