如何在 java 中使用 lambda 表达式缩写数据处理代码?



我在空白空间中使用lambda表达式编写逻辑上相同的代码时遇到问题。 如何使用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::getSex));

这称为链接。

最新更新