问题描述
我想在一个列表中搜索,我的列表看起来像
I want to search in a List and my List is look like
List<Employee> oneEmp= new ArrayList<Employee>();
List<Employee> twoEmp= new ArrayList<Employee>();
oneEmp= [Employee [eid=1001, eName=Sam Smith, eAddress=Bangluru, eSalary=10000000], Employee [eid=0, eName=, eAddress=, eSalary=null], Employee [eid=1003, eName=Amt Lime, eAddress=G Bhagyoday, eSalary=200000], Employee [eid=1004, eName=Ash Wake, eAddress=BMC, eSalary=200000], Employee [eid=1005, eName=Will Smith, eAddress= Delhi, eSalary=200000], Employee [eid=1006, eName=Shya Ymwar, eAddress=Madras, eSalary=50000], Employee [eid=1007, eName=Nag Gam, eAddress=Pune, eSalary=10000000], Employee [eid=1008, eName=Arti, eAddress=Delhi, eSalary=10000000]]
twoEmp= [Employee [eid=0, eName=null, eAddress=null, eSalary=100000], Employee [eid=0, eName=null, eAddress=null, eSalary=50000], Employee [eid=0, eName=null, eAddress=null, eSalary=200000]]
我正在使用这样的代码:-
I am using code like this:-
for(Employee two : twoEmp){
for (Iterator<Employee> iterator = oneEmp.iterator(); iterator.hasNext(); ) {
Employee e = iterator.next();
if (e.geteSalary() != null && two.geteSalary() != null && e.geteSalary().compareTo(two.geteSalary()) == 0) {
finalEmpList.add(e);
}
}
}
但这仍然需要 2 个 for 循环
But this still required 2 for loop
我使用的是 JAVA 1.6
我的员工类有属性:
//Employee class
int eid;
BigInteger eSalary;
String eName, eAddress;
现在我想获取 List who's Salary = 10000000 中的所有对象
Now I want to get all the objects in List who's Salary = 10000000
结果应该是:
[员工 [eid=1001,eName=Sam Smith,eAddress=Bangluru,eSalary=10000000],员工 [eid=1007,eName=Nag Gam,eAddress=Pune,eSalary=10000000],员工 [eid=1008,eName=Arti, eAddress=Del eSalary=10000000],.................................]
[Employee [eid=1001, eName=Sam Smith, eAddress=Bangluru, eSalary=10000000], Employee [eid=1007, eName=Nag Gam, eAddress=Pune, eSalary=10000000], Employee [eid=1008, eName=Arti, eAddress=Del eSalary=10000000],.........................]
我想在不使用任何循环或所需的最小循环的情况下实现此目的,因为数据会很大
I would like to achieve this without using any loop or minimum loop required because data will be large
推荐答案
是的,使用 流.
首先,考虑使用泛型集合:
First, consider using a generic collection:
List<Employee> employees = new ArrayList<>():
//add all employees to the list
现在您可以使用流 过滤你的列表
Now you can use streams to filter your list
List<Employee> filtered = employees.stream()
.filter(emp -> emp.getSalary() == 10000000)
.collect(Collectors.toList());
可能 Stream 库仍在内部使用某种循环,但虽然它的实现对我来说是隐藏的,但我并不担心.
Probably Stream library is still using some kind of loop internally but while its implementation is hidden from me I do not worry.
这篇关于如何在列表中搜索,我的列表如下所示:List<Object>myList = new ArrayList<Object>()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!