如何先分组,然后使用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) 我有几个类,如下
class Pojo {
List<Item> items;
}
class Item {
T key1;
List<SubItem> subItems;
}
class SubItem {
V key2;
Object otherAttribute1;
}
Run Code Online (Sandbox Code Playgroud)
我想根据key1每个聚合聚合项目,子项目应按key2以下方式聚合:
Map<T, Map<V, List<Subitem>>
Run Code Online (Sandbox Code Playgroud)
Java 8 Collectors.groupingBy嵌套有什么可能吗?
我正在尝试一些东西并且中途停留
pojo.getItems()
.stream()
.collect(
Collectors.groupingBy(Item::getKey1, /* How to group by here SubItem::getKey2*/)
);
Run Code Online (Sandbox Code Playgroud)
注意:这与级联不同groupingBy,后者根据此处讨论的同一对象中的字段进行多级聚合
我想确定显示点集合所需的最小区域.简单的方法是循环遍历集合,如下所示:
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (Point point: points) {
if (point.x < minX) {
minX = point.x;
}
if (point.x > maxX) {
maxX = point.x;
}
if (point.y < minY) {
minY = point.y;
}
if (point.y > maxY) {
maxY = point.y;
}
}
Run Code Online (Sandbox Code Playgroud)
我开始了解溪流.要做到这一点,您可以执行以下操作:
int minX = points.stream().mapToInt(point -> point.x).min().orElse(-1);
int maxX = points.stream().mapToInt(point -> point.x).max().orElse(-1);
int minY = points.stream().mapToInt(point -> point.y).min().orElse(-1);
int maxY …Run Code Online (Sandbox Code Playgroud)