java根据list中的对象某个属性分组,每组取另一个属性最高的值
时间: 2023-08-20 14:07:08 浏览: 201
java根据List内对象的属性排序方法
5星 · 资源好评率100%
可以按照以下步骤实现:
1. 使用Java 8的stream API将list按照某个属性分组,可以使用Collectors.groupingBy()方法实现,例如假设要根据对象的category属性进行分组,可以这样写:
```java
Map<String, List<MyObject>> groups = list.stream()
.collect(Collectors.groupingBy(MyObject::getCategory));
```
2. 遍历分组后的Map,对于每个分组,使用stream API获取该分组中另一个属性最高的对象。可以使用Collectors.maxBy()方法实现,例如假设要获取对象的value属性最高的对象,可以这样写:
```java
Map<String, MyObject> result = new HashMap<>();
for (Map.Entry<String, List<MyObject>> entry : groups.entrySet()) {
MyObject maxObj = entry.getValue().stream()
.collect(Collectors.maxBy(Comparator.comparing(MyObject::getValue)))
.orElse(null);
result.put(entry.getKey(), maxObj);
}
```
完整代码示例:
```java
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<MyObject> list = Arrays.asList(
new MyObject("A", "C1", 10),
new MyObject("A", "C2", 20),
new MyObject("B", "C1", 30),
new MyObject("B", "C2", 40)
);
Map<String, List<MyObject>> groups = list.stream()
.collect(Collectors.groupingBy(MyObject::getCategory));
Map<String, MyObject> result = new HashMap<>();
for (Map.Entry<String, List<MyObject>> entry : groups.entrySet()) {
MyObject maxObj = entry.getValue().stream()
.collect(Collectors.maxBy(Comparator.comparing(MyObject::getValue)))
.orElse(null);
result.put(entry.getKey(), maxObj);
}
System.out.println(result);
}
}
class MyObject {
private String category;
private String name;
private int value;
public MyObject(String category, String name, int value) {
this.category = category;
this.name = name;
this.value = value;
}
public String getCategory() {
return category;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String toString() {
return category + " " + name + " " + value;
}
}
```
输出结果:
```
{A=MyObject@28d93b30[C2 20], B=MyObject@1b6d3586[C2 40]}
```
阅读全文