2

I have some object Tag

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;
}
}

And have two lists List<Tag> firstList and List<Tag> secondList I have to compare them only by name and create thirdList which will contain unique objects from the firstList. How can I do this by means of stream?

SOLUTION:

List<Tag> thirdList = firstList.stream()
        .filter(f -> secondList.stream()
                .noneMatch(t -> t.getName().equals(f.getName())))
        .collect(Collectors.toList());
Naman
  • 27,789
  • 26
  • 218
  • 353
Igor Tsalko
  • 45
  • 1
  • 7

1 Answers1

0

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 + '\'' +
                '}';
    }
}
MrFisherman
  • 720
  • 1
  • 7
  • 27