java8写一段按n个key作为组合key,组合key变化时只保留最新一条数据的共通方法
时间: 2024-05-09 20:19:28 浏览: 41
假设有一个数据类Data,其中包含n个key(key1、key2、key3……keyn)和一些其他属性。我们可以使用Java 8的Stream API实现按n个key作为组合key,组合key变化时只保留最新一条数据的方法。
首先,我们需要按照n个key对数据进行分组,可以使用Collectors.groupingBy()方法来实现:
```
Map<List<Object>, List<Data>> groups = dataList.stream()
.collect(Collectors.groupingBy(data -> Arrays.asList(data.getKey1(), data.getKey2(), data.getKey3(), ……, data.getKeyn())));
```
这将返回一个Map,其中的key是由n个key组成的List,value是相应的数据列表。
接下来,我们需要从每个组中只保留最新的数据。我们可以使用Collectors.toMap()方法来实现,但需要指定一个合并函数,以处理两个相同组合key的数据:
```
List<Data> result = groups.values().stream()
.map(group -> group.stream().reduce((d1, d2) -> d1.getTimestamp() > d2.getTimestamp() ? d1 : d2).orElse(null))
.collect(Collectors.toList());
```
这将返回一个包含最新数据的List。
完整代码如下:
```
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Data> dataList = Arrays.asList(
new Data("key1", "key2", "key3", "value1", 1000),
new Data("key1", "key2", "key3", "value2", 2000),
new Data("key1", "key2", "key3", "value3", 1500),
new Data("key4", "key5", "key6", "value4", 3000),
new Data("key4", "key5", "key6", "value5", 2500),
new Data("key7", "key8", "key9", "value6", 4000)
);
List<Data> result = dataList.stream()
.collect(Collectors.groupingBy(data -> Arrays.asList(data.getKey1(), data.getKey2(), data.getKey3())))
.values().stream()
.map(group -> group.stream().reduce((d1, d2) -> d1.getTimestamp() > d2.getTimestamp() ? d1 : d2).orElse(null))
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
class Data {
private String key1;
private String key2;
private String key3;
private String value;
private long timestamp;
public Data(String key1, String key2, String key3, String value, long timestamp) {
this.key1 = key1;
this.key2 = key2;
this.key3 = key3;
this.value = value;
this.timestamp = timestamp;
}
public String getKey1() {
return key1;
}
public String getKey2() {
return key2;
}
public String getKey3() {
return key3;
}
public String getValue() {
return value;
}
public long getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return "Data{" +
"key1='" + key1 + '\'' +
", key2='" + key2 + '\'' +
", key3='" + key3 + '\'' +
", value='" + value + '\'' +
", timestamp=" + timestamp +
'}';
}
}
```
输出结果为:
```
Data{key1='key1', key2='key2', key3='key3', value='value2', timestamp=2000}
Data{key1='key4', key2='key5', key3='key6', value='value4', timestamp=3000}
Data{key1='key7', key2='key8', key3='key9', value='value6', timestamp=4000}
```
阅读全文