, 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"}
Edit
, :
hashCode()
equals(..)
Object:
...
@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());
petsList.removeAll(newList);
petsList.addAll(0, newList);