首页 > 解决方案 > 如何使用 java 8 准备使用两个列表的第三个列表

问题描述

我有两个不同的列表,并使用那些我使用流准备第三个列表的列表。

学生.java

public class Student {

    int id;
    String name;

    public Student(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

StudentLoc.java

public class StudentLoc {

    int id;
    String loc;

    public StudentLoc(int id, String loc) {
        super();
        this.id = id;
        this.loc = loc;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

}

我有像下面这样的三等舱。

StudentDetLoc.java

public class StudentDetLoc {

    int id;
    String name;
        String Loc;

}
  1. 我必须使用 id 属性比较 Student 列表和 StudentLoc 列表。
  2. 如果两个列表中都存在 id,那么我必须使用两个列表来准备 StudentDetLoc 列表。

标签: javacollections

解决方案


我的方法是:

  1. streams()使用和从第一个列表中创建一组学生 IDmap()
  2. filter()使用从步骤 1 获得的集合过滤第二个列表
  3. 用作步骤 2 的终止操作forEach()并附加到最​​终的第三个列表(仅保留和id)。nameLoc

推荐阅读