Java 将两个对象list里面的 某个字段值抽取到一个list里

x33g5p2x  于2021-11-21 转载在 Java  
字(2.4k)|赞(0)|评价(0)|浏览(625)

场景举例:

两个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());
    }
}

输出结果: 

ps:

同样,如果来自一个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());

相关文章