如何先分组,然后使用Java流应用过滤?
示例:考虑此类Employee:我希望按部门分组,其中包含薪水大于2000的员工列表.
public class Employee {
private String department;
private Integer salary;
private String name;
//getter and setter
public Employee(String department, Integer salary, String name) {
this.department = department;
this.salary = salary;
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我如何做到这一点
List<Employee> list = new ArrayList<>();
list.add(new Employee("A", 5000, "A1"));
list.add(new Employee("B", 1000, "B1"));
list.add(new Employee("C", 6000, "C1"));
list.add(new Employee("C", 7000, "C2"));
Map<String, List<Employee>> collect = list.stream()
.filter(e -> e.getSalary() > 2000)
.collect(Collectors.groupingBy(Employee::getDepartment));
Run Code Online (Sandbox Code Playgroud)
产量
{A=[Employee [department=A, salary=5000, name=A1]],
C=[Employee [department=C, …Run Code Online (Sandbox Code Playgroud) 在Java 8中,有没有办法根据条件在流上应用过滤器,
例
我有这个流
if (isAccessDisplayEnabled) {
src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
.filter(k - > isAccessDisplayEnabled((Source) k))
.filter(k - > containsAll((Source) k, substrings, searchString))
.collect(Collectors.toList());
} else {
src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
.filter(k - > containsAll((Source) k, substrings, searchString))
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
我正在添加过滤器
.filter(k - > isAccessDisplayEnabled((Source) k)))
Run Code Online (Sandbox Code Playgroud)
在基于if-else条件的流上.有没有办法避免if-else,因为如果有更多的过滤器出现,那么它将很难维护.
请告诉我
在我之前的问题 - 如何使用列表在地图中分组时过滤年龄我能够找到使用年龄组的名称List<User> users.现在我试图根据阈值从年龄中找到不同的用户组.我试过这个
List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());
Run Code Online (Sandbox Code Playgroud)
这次它可以工作,我可以看到使用
userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
Run Code Online (Sandbox Code Playgroud)
但我必须再次访问用户列表才能找到免费列表.这可以做得更简单吗?
我有一个具有名称,类型和年龄的User类,然后这些用户的一长串就是我的输入。List<User> users = db.getUsers();
我正在尝试以此创建一组所有唯一用户,但是问题是我也在寻找根据年龄对他们进行排序。我目前使用过-
Set<User> set = users.stream().collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)
如何同时对这个集合排序,有什么想法吗?