java - 按名称比较两个对象列表并获取不同对象的列表
问题描述
我有一些对象标签
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> firstList
,List<Tag> secondList
我必须仅按名称比较它们并创建thirdList
将包含来自firstList
. 我怎样才能通过流来做到这一点?
解决方案:
List<Tag> thirdList = firstList.stream()
.filter(f -> secondList.stream()
.noneMatch(t -> t.getName().equals(f.getName())))
.collect(Collectors.toList());
解决方案
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 + '\'' +
'}';
}
}
推荐阅读
- java - 我可以编写 Error 对象以在 catch 块中捕获 Exception 对象吗
- php - github php buildpack 支持 DB2 和 IBM Cloud php 应用程序
- arangodb - 2个集合之间的ARANGO DB关系
- php - 如何根据 user_id 或主题获取数据
- swift - 如何以编程方式查找视图的纵横比?
- ionic3 - 如何使用城市名称搜索离子存储并获取城市 ID
- javascript - 在 Windows/Linux 机器的 Canvas 中渲染时提高线条清晰度(设备像素比 < 2)?
- python - Tkinter 用 Selenium python 冻结
- php - 无法上传数据库中的文件
- python-3.x - 在 python 中更新 AWS Lambda 函数的环境变量