【问题标题】:How to abbreviate data processing code using lambda expression in java?如何在java中使用lambda表达式缩写数据处理代码?
【发布时间】: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&lt;Student.Sex, List&lt;Student&gt;&gt; mapBySexWithLambda = totalList.stream().collect(Collectors.groupingBy(student -&gt; student.getSex()))

标签: java lambda stream


【解决方案1】:

这就是你如何在一行中做到的:

Map<Student.Sex, List<Student>> mapBySexWithLambda = totalList.stream().collect(Collectors.groupingBy(Student::getSex));

这称为链接。

【讨论】:

  • @Mustahsan 同意。
猜你喜欢
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
  • 2022-10-15
相关资源
最近更新 更多