vye*_*man 3 java arrays spring arraylist
我有一个带有一些 @RequestParam(required = false) 的控制器,它必须返回带有一些过滤器的所有药物(如果存在),该控制器的服务,其中包含它的逻辑,但它不起作用。主要问题是我有 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();
}
Run Code Online (Sandbox Code Playgroud)
该Collection#retainAll()方法只会保留另一个中出现的项目Collection;换句话说,两个集合的交集。使用它两次可以获得三个集合的交集:
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |