[英]Common part from three ArrayList
我有一個帶有一些 @RequestParam(required = false) 的 controller,如果它們存在,則必須返回所有帶有一些過濾器的葯物,為此 controller 提供服務,其中包含它的邏輯,但它不起作用。 主要問題是我有 3 個 ArrayList 並且我無法想出如何找到所有三個 ArrayList 中存在的所有元素:)
public List<Medicine> readAllMedicine(Double lessThenPrice, Double moreThenPrice, String name) {
//when lessThenPrice < moreThenPrice, result of their queries will not have general elements
if ((lessThenPrice != null && moreThenPrice != 0) && lessThenPrice < moreThenPrice) {
return Collections.emptyList();
}
List<Medicine> resultList = new ArrayList<>();
List<Medicine> lessList = new ArrayList<>();
List<Medicine> moreList = new ArrayList<>();
List<Medicine> nameList = new ArrayList<>();
//checking if there are arguments from the controller
if (lessThenPrice != null) {
lessList.addAll(medicineDao.findMedicinesByPriceIsLessThan(lessThenPrice));
}
if (moreThenPrice != null) {
moreList.addAll(medicineDao.findMedicinesByPriceIsGreaterThan(moreThenPrice));
}
if (name != null) {
nameList.addAll(medicineDao.findMedicinesByName(name));
}
//saving general elements
//this part is not working
if (!lessList.isEmpty() || !moreList.isEmpty() || !nameList.isEmpty()) {
List<Medicine> temp = new ArrayList<>(); //it will contain general part of lessList and moreList
for (Medicine medicine : lessList) {
if (moreList.contains(medicine)) {
temp.add(medicine);
}
}
for (Medicine medicine : nameList) {
if (temp.contains(medicine)) {
resultList.add(medicine);
}
}
return resultList;
}
//if there is no args, just return all medicines
return medicineDao.findAll();
}
從多個列表中獲取所有公共元素的一種選擇是迭代第一個列表並過濾掉所有其他列表中存在的元素,因此:
List<Medicine> resultList = lessList.stream()
.filter(moreList::contains)
.filter(namesList::contains)
.collect(Collectors.toList());
雖然這可行,但對於更大的列表,您可以考慮使用HashSets
而不是列表,以獲得更好的性能。
此外,此代碼假定Medicine
class 對equals
和hashcode
具有正確的實現。
Collection#retainAll()
方法只會保留出現在另一個Collection
中的項目; 也就是說,兩個collections的交集。 用它兩次得到三個collections的交集:
List<String> list1 = List.of("a", "b", "c", "q");
List<String> list2 = List.of("b", "d", "e", "q");
List<String> list3 = List.of("b", "q", "r", "s");
List<String> intersection = new ArrayList<String>(list1);
intersection.retainAll(list2);
intersection.retainAll(list3);
System.out.println(intersection); // [b, q]
最好的方法是使用retainAll 方法從列表中消除所有不常見的項目。 https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#retainAll(java.util.Collection)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.