如何检索列表中具有某些属性的所有对象?

时间:2017-05-17 10:05:01

标签: java list object

例如,我已经创建了一个"事件列表"来自服务门户网站:

List<Incident> incidentObjectList = new ArrayList<>();
for (int i = 0; i < incidentNumberList.size(); i++) {
    Incident incident = new Incident();
    incident.setIncidentNumber(incidentNumberList.get(i));
    incident.setSummary(summaryList.get(i));
    incident.setRequestId(requestIdList.get(i));
    incident.setPriority(priorityList.get(i));
    incident.setLastModifiedDate(lastModifiedDateList.get(i));
    incidentObjectList.add(incident);
}
System.out.println("Incident Object List" + incidentObjectList);

每个突发事件都有几个属性,但我只希望从原始列表创建一个新列表,该列表由优先级为Low的突发事件对象组成。在这种情况下,incident.getPriority()将为新列表中的所有对象返回字符串Low

String[] dataGreenArray = incidentObjectList.get();
retrieveTickets(dataGreenArray, listViewGreen);

2 个答案:

答案 0 :(得分:3)

在Java 8中

List<Incident> list = incidentObjectList.stream()
                                        .filter(e->e.getPriorty().equals("Low"))
                                        .collect(Collectors.toList());

答案 1 :(得分:2)

循环遍历incidentObjectList并检查每个元素的优先级。

for (Incident incident: incidentObjectList)
{
    if (incident.getPriority().equals("Low")
        desiredList.add(incident);         // or whatever you want to do
}

这是一个非常基本的解决方案,但除非您专门寻找其他内容,否则它应该有效。希望它有所帮助!