天天看點

Java 将兩個對象list裡面的 某個字段值抽取到一個list裡

場景舉例:

兩個List(rooms1 和 rooms2)裡面放的對象都是 Room ,

現在想把兩個List裡面的 room 的id 都抽取出來,放在一個List裡面 。

實作代碼:

List<Integer> idList = Stream.concat(rooms1.stream().map(Room::getId), rooms2.stream().map(Room::getId)).collect(Collectors.toList());      

List<Integer> idList =  Stream.of(rooms1, rooms2).flatMap(List::stream).map(Room::getId).collect(Collectors.toList());      

例子:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author JCccc
 * @Description
 * @Date 2021/8/20 9:05
 */

public class Room {

    private Integer id;
    private String name;
    private Short type;


    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Short getType() {
        return type;
    }

    public void setType(Short type) {
        this.type = type;
    }


    public static void main(String[] args) {

        List<Room> rooms1=new ArrayList<>();
        Room roomA=new Room();
        roomA.setId(1);
        roomA.setName("1-A");
        roomA.setType((short)1);
        Room roomB=new Room();
        roomB.setId(2);
        roomB.setName("2-A");
        roomB.setType((short)1);

        rooms1.add(roomA);
        rooms1.add(roomB);


        List<Room> rooms2=new ArrayList<>();
        Room roomC=new Room();
        roomC.setId(3);
        roomC.setName("3-C");
        roomC.setType((short)2);
        Room roomD=new Room();
        roomD.setId(4);
        roomD.setName("4-D");
        roomD.setType((short)2);

        rooms2.add(roomC);
        rooms2.add(roomD);


        //去重set (注意真正操作時需要對倆list做判空校驗)
        List<Integer> idList=new ArrayList<>(Stream.concat(rooms1.stream().map(Room::getId), rooms2.stream().map(Room::getId)).collect(Collectors.toSet()));

        //去重set (注意真正操作時需要對倆list做判空校驗)
        List<Integer> idList=new ArrayList<>( Stream.of(rooms1, rooms2).flatMap(List::stream).map(Room::getId).collect(Collectors.toSet()));

        //不去重list
        //  List<Integer> idList = Stream.concat(rooms1.stream().map(Room::getId), rooms2.stream().map(Room::getId)).collect(Collectors.toList());
        System.out.println(idList.toString());
    }
}      

輸出結果: 

Java 将兩個對象list裡面的 某個字段值抽取到一個list裡
List<Room> rooms1=new ArrayList<>();
Room roomA=new Room();
roomA.setId(1);
roomA.setName("1-A");
roomA.setType((short)1);
roomA.setFid(5);

Room roomB=new Room();
roomB.setId(2);
roomB.setName("2-A");
roomB.setType((short)1);
roomB.setFid(10);
rooms1.add(roomA);
rooms1.add(roomB);

List<Integer> idList = Stream.concat(rooms1.stream().map(Room::getId), rooms1.stream().map(Room::getFid)).collect(Collectors.toList());