我正在进行以下两个操作
- 遍历对象列表并根据条件创建
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());
在O(1(中,最好从nameList
创建一个集合,使contains()
运算更快
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"));
然后是nameList。注意,最好将其放在的集合中
- 避免重复,并且
- 使查找过程更加高效
Set<String> nameSet = Set.of("Joe", "Anne", "Ralph");
现在可以使用
- 筛选有效人员与无效人员
- 将这些人映射到一个名字
- 过滤是否为null,然后过滤名称是否在名称集中
- 并放置在列表中
注意:在某些情况下,根据方法类型和调用上下文,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;
}
}