用java查找两个list对象中,各有一个string属性,以list1为主查找,在list2中没有list1的属性
时间: 2023-11-25 18:07:00 浏览: 26
可以使用Java 8的Stream API来实现这个功能。具体步骤如下:
1. 首先将list2中所有的属性值放入一个集合中,方便后面进行比较。
```
List<String> list2Properties = list2.stream()
.map(Item::getProperty)
.collect(Collectors.toList());
```
2. 然后使用filter方法过滤出所有list1中的属性值,在list2中不存在的。
```
List<Item> notInList2 = list1.stream()
.filter(item -> !list2Properties.contains(item.getProperty()))
.collect(Collectors.toList());
```
完整代码如下:
```
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Item> list1 = new ArrayList<>();
list1.add(new Item("A"));
list1.add(new Item("B"));
list1.add(new Item("C"));
List<Item> list2 = new ArrayList<>();
list2.add(new Item("B"));
list2.add(new Item("D"));
List<String> list2Properties = list2.stream()
.map(Item::getProperty)
.collect(Collectors.toList());
List<Item> notInList2 = list1.stream()
.filter(item -> !list2Properties.contains(item.getProperty()))
.collect(Collectors.toList());
System.out.println(notInList2); // 输出 [Item{property='A'}, Item{property='C'}]
}
}
class Item {
private String property;
public Item(String property) {
this.property = property;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
@Override
public String toString() {
return "Item{" +
"property='" + property + '\'' +
'}';
}
}
```
其中,Item类是代表具有一个属性的对象。在这个例子中,属性的类型是String,通过getProperty方法获取。