使用java流组合到操作
我正在做下面两个手术使用java流组合到操作,java,java-8,java-stream,Java,Java 8,Java Stream,我正在做下面两个手术 迭代对象列表并根据条件创建字符串、布尔值的映射 Map myMap=newhashmap(); 迭代器迭代器=personList.Iterator(); while(iterator.hasNext()){ Person=iterator.next(); if(有效人员){ if(person.getName()!=null){ myMap.put(person.getName(),true); }否则{ myMap.put(person.getName(),false)
字符串、布尔值的映射
Map myMap=newhashmap();
迭代器迭代器=personList.Iterator();
while(iterator.hasNext()){
Person=iterator.next();
if(有效人员){
if(person.getName()!=null){
myMap.put(person.getName(),true);
}否则{
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);
}
}
List-definedList=new-ArrayList();
用于(字符串名称:名称列表){
if(myMap.get(name)!=null&&myMap.get(name)){
添加(名称);
}
}
我需要使用Java流简化逻辑。否则,上述方法可以正常工作。您可以通过在
名称列表中选中“包含”来直接筛选列表,并在列表中收集名称
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());
注意:如果姓名列表
不包含重复项,则此操作有效。在第一个操作中,您将筛选出所有无效人员,并将有效人员收集到地图中,因此:
Map<String,Boolean> myMap = personList.stream()
.filter(YourClass::isValidPerson)
.collect(Collectors.toMap(x -> x.getName(), x -> x.getName() != null))
然后,您可以使用O(1)时间轻松检查包含的:
List-definedList=nameList.stream().filter(mySet::contains).collect(Collectors.toList());
这应该行得通
首先,创建一个人员列表
List<Person> personList = List.of(new Person("Joe"),
new Person(null), new Person("Barb"), new Person("Anne"), new Person("Gary"));
印刷品
[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;
}
}
你为什么需要这张地图?难道你不能直接把那些有效的、名字不为空的人添加到refinedList
?@Sweeper在代码的第二部分,我实际上循环了另一个名字列表,检查他们在地图上的位置用于(字符串名称:名称列表){`您已经改变了代码的逻辑,不是吗?代码应该获取姓名列表
的所有元素,即有效人名,而不是获取姓名列表
元素的所有有效人名。例如,如果姓名列表
包含重复项,该代码将产生不同的结果。或者e> nameList.retainAll(mySet)
,之后不需要原始列表。
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");
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;
}
}