[英]How to use java stream to filter object?
java中如何使用过滤器来过滤完整的对象。 我有一个包含name
和amount
的 ArrayList ,我有另一个包含一些字符串的字符串数组。
现在在这里如何过滤和创建一个新的 ArrayList,它只包含这两个具有arr
元素的对象。
我尝试使用两种方法.equals
和.contains
但它不产生输出。
List<Person> people = new ArayList<>();
people.add(new Person("Warren Buffett" , 90));
people.add(new Person("Jeff Bezos" , 180));
people.add(new Person("Bill Gates" , 140));
people.add(new Person("Mark" , 120));
String arr[]={"Mark" , "Bill Gates"};
List<Person> newPeople = people.stream().filter(person -> person.name.equals(arr))
List<Person> newPeople = people.stream().filter(person -> person.name.contains(arr)).collect(collectors.toList());
newPeople.forEach(person -> System.out.println(person.name));
编辑:
我应该将输出作为一个对象的数组,该对象应该包含马克和比尔盖茨的名字及其数量
你不能做这个person.name.contains(arr)
,而你应该做person.name.contains(arr[0])
或person.name.contains(arr[1])
。
为此,您可能需要进行嵌套迭代。
您可以在下面找到工作解决方案。 使用流通过 args 数组进行迭代以查找第一个匹配的 arg。
List<Person> newPeople = people.stream()
.filter(person -> Stream.of(arr).anyMatch(s -> person.name.equals(s)))
.collect(Collectors.toList());
newPeople.forEach(person -> System.out.println(person.name));
// Bill Gates
// Mark
您可以将数组转换为列表; 然后使用List.contains()
检查该list
的person.name
是否可用。
首先转换数组。
String arr[]={"Mark" , "Bill Gates"};
List<String> names = Arrays.asList(arr);
现在,使用List.contains()
List<Person> newPeople
= people.stream().filter(
person -> names.contains(person.name)).collect(Collectors.toList()
);
以下是更新后的完整方法。
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Warren Buffett" , 90));
people.add(new Person("Jeff Bezos" , 180));
people.add(new Person("Bill Gates" , 140));
people.add(new Person("Mark" , 120));
String arr[]={"Mark" , "Bill Gates"};
List<String> names = Arrays.asList(arr);
List<Person> newPeople = people.stream().filter(person -> names.contains(person.name)).collect(Collectors.toList());
newPeople.forEach(person -> System.out.println(person.name));
}
所以你想要一个只包含名字出现在 arr 中的 Person 实例的新列表? 尝试这样做:
List<Person> newPeople = people.stream()
.filter(person -> arr.contains(person.name))
.collect(collectors.toList());
lambda 变量“person”指的是包含在人员列表中的单个对象,而不是列表本身。 因此,当您使用 person.name.equals(...) 或 person.name.contains(...) 时,您是在字符串上调用这些方法。 反过来,就像我的例子一样,会给你想要的结果; 如果没有,让我们知道,我们会挖北斗七星
编辑:
我假设 arr 是一个列表,因此在使用我的代码之前,您应该考虑执行以下操作
List<String> names = Arrays.asList(arr);
进而
List<Person> newPeople = people.stream()
.filter(person -> names.contains(person.name))
.collect(collectors.toList());
假设您正在通过其他东西传递该数组,如果您正在创建它,您可以创建一个列表并跳过数组“步骤”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.