首先从第二个列表中删除第一个列表的所有元素,然后创建一个LinkedList(保持顺序)将其余元素组合在一起:
List<Pets> resultList = new LinkedList<>();
List<Pets> firstList = {"cats", "mice"};
List<Pets> secondList = {"dogs", "cats", "parrots", "mice", "hamsters", "guinea pigs"};
secondList.removeAll(firstList);//{"dogs", "parrots", "hamsters", "guinea pigs"}
resultList.addAll(firstList);//{"cats", "mice"}
resultList.addAll(secondList);//{"cats", "mice", "dogs", "parrots", "hamsters", "guinea pigs"}
编辑
您可以按照以下步骤解决您的问题:
- 您的类 Object 中的用户
hashCode() 和 equals(..) 方法如下:
...
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + Objects.hashCode(this.name);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pet other = (Pet) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
...
- 然后从主体列表中查找所有元素
- 删除它们
- 然后将它们添加到顶部
这是使用 Java 8 的一种方式:
List<Pet> namesList = new LinkedList<>(
Arrays.asList(
new Pet("cats", 0, 0),
new Pet("mice", 0, 0)
)
);
List<Pet> petsList = new LinkedList<>(
Arrays.asList(
new Pet("dogs", 16, 18),
new Pet("cats", 36, 99),
new Pet("parrots", 85, 25),
new Pet("mice", 70, 28),
new Pet("hamsters", 12, 41),
new Pet("guinea pigs", 75, 95)
)
);
List<Pet> newList = petsList.stream()
.filter(t -> namesList.contains(t))
.collect(Collectors.toList());//find the necessary objects
petsList.removeAll(newList);//remove them from the principal list
petsList.addAll(0, newList);//add the result on the top
Check the demo code