[英]Combining to operations using java streams
我正在做以下两个操作
String, Boolean
的映射。 Map<String,Boolean> myMap = new HashMap<>();
Iterator<Person> iterator = personList.iterator();
while (iterator.hasNext()) {
Person person = iterator.next();
if (isValidperson(person)) {
if (person.getName() != null) {
myMap.put(person.getName(), true);
} else {
myMap.put(person.getName(), false);
}
}
}
现在我根据我在上面创建的地图检查名称列表,如果值为真,则添加到最终列表
List<String> refinedList = new ArrayList<>();
for (String name : nameList) {
if (myMap.get(name) != null && myMap.get(name)) {
refinedList.add(name);
}
}
我需要使用 Java 流来简化逻辑。 否则以上工作正常。
在第一个操作中,您将过滤掉所有无效人员,并将有效人员收集到地图中,因此:
Map<String,Boolean> myMap = personList.stream()
.filter(YourClass::isValidPerson)
.collect(Collectors.toMap(x -> x.getName(), x -> x.getName() != null))
但实际上,地图最多只有一个false
条目,因为您不能将多个null
添加到HashMap
,因此使用HashMap
根本没有多大意义。
我建议使用HashSet
:
Set<String> mySet = personList.stream()
.filter(YourClass::isValidPerson)
.map(Person::getName)
.filter(Objects::nonNull)
.collect(Collectors.toSet())
然后你可以很容易地用 O(1) 时间检查contains
:
List<String> refinedList = nameList.stream().filter(mySet::contains).collect(Collectors.toList());
您可以通过检查nameList
包含来直接过滤列表并收集列表中的名称
List<String> refinedList =
personList.stream()
.filter(e -> isValidperson(e))
.map(e -> e.getName())
.filter(Objects::nonNull)
.distinct()
.filter(e -> nameList.contains(e))
.collect(Collectors.toList());
并且最好从nameList
创建一个集合以使contains()
操作在 O(1) 中更快
Set<String> nameSet = new HashSet<String>(nameList);
注意:如果nameList
不包含重复项,这将起作用。
这应该有效。
首先,创建一个人员列表。
List<Person> personList = List.of(new Person("Joe"),
new Person(null), new Person("Barb"), new Person("Anne"), new Person("Gary"));
然后是名称列表。 注意最好把它放在一个集合中
Set<String> nameSet = Set.of("Joe", "Anne", "Ralph");
现在这有效
注意:在某些情况下,根据方法类型和调用上下文,可以将lambdas
替换为Method References
。
List<String> names = personList.stream()
.filter(person -> isValidperson(person))
.map(Person::getName)
.filter(name -> name != null && nameSet.contains(name))
.collect(Collectors.toList());
System.out.println(names);
印刷
[Joe, Anne]
虚拟方法,因为未提供标准
public static boolean isValidperson(Person person) {
return true;
}
简单的人类
class Person {
String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.