首页 > 解决方案 > 按名称比较两个对象列表并获取不同对象的列表

问题描述

我有一些对象标签

public class Tag {

private int id;
private String name;

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    return this;
}
}

并且有两个列表List<Tag> firstListList<Tag> secondList 我必须仅按名称比较它们并创建thirdList将包含来自firstList. 我怎样才能通过流来做到这一点?

解决方案

List<Tag> thirdList = firstList.stream()
        .filter(f -> secondList.stream()
                .noneMatch(t -> t.getName().equals(f.getName())))
        .collect(Collectors.toList());

标签: javalambdajava-streamcompare

解决方案


You can do it like this:

List<Tag> a = List.of(new Tag(1, "tag1"), new Tag(2, "tag2"));
List<Tag> b = List.of(new Tag(1, "tag1"), new Tag(3, "tag3"), new Tag(4, "tag4"));

Set<Tag> collect = a.stream()
       .filter(x -> !b.contains(x))
       .collect(Collectors.toSet());

System.out.println(collect);

and have to implement equals and hashCode for Tag:

class Tag {

    private int id;
    private String name;

    public Tag(int id, String name) {
        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;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Tag tag = (Tag) o;
        return Objects.equals(name, tag.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public String toString() {
        return "Tag{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

推荐阅读