使用 inputMap(键和值可能因每个请求而异)过滤列表 (List1) 中的数据


class Person
{
private String name;
private String birthDate;
private String city;
private String state;
private int zipCode;    
}
Map<String, String> inputMap = new HashMap<>();
inputMap.put(“name”, “David”);
Map<String, String> inputMap1 = new HashMap<>();
inputMap1.put(“name”, “David”);
inputMap1.put(“city”, “Auburn”);

我将从数据库中获取人员列表,下面的地图是输入(此输入地图是动态的。我们可能会只得到城市或城市和邮政编码或上述 Person 对象中定义的 5 个属性的任意组合(

我需要使用流过滤与输入地图匹配的人员列表。我尝试了使用 java 流的不同方法,但没有运气,请帮忙。

您可以为Map中的每个可能的键应用过滤器(即您需要 5 个filter操作(:

List<Person> input = ...
List<Person> filtered = input.stream()
.filter(p -> !inputMap.containsKey("name") || p.getName().equals(inputMap.get("name")))
.filter(p -> !inputMap.containsKey("city") || p.getCity().equals(inputMap.get("city")))
...
.collect(Collectors.toList());

如果要对任意数量的Map键进行通用化,则需要另一个将键映射到Person的相应属性的Map

例如,如果您有:

Map<String,Function<Person,Object>> propMap = new HashMap<>();
propMap.put ("name",Person::getName);
propMap.put ("city",Person::getCity);
...

你可以这样写:

List<Person> filtered = input.stream()
.filter(p -> inputMap.entrySet()
.stream()
.allMatch(e -> propMap.get(e.getKey()).apply(p).equals(e.getValue())))
.collect(Collectors.toList());

这意味着对于inputMap的每个键,Person实例的相应属性(通过propMap.get(key).apply(p)获得,其中pPerson(必须等于该键的值。

最新更新