使用treeset去重保留最新的数据
时间: 2024-03-05 18:53:21 浏览: 21
可以通过实现自定义的Comparator来实现使用TreeSet去重并保留最新的数据。下面是一个示例代码:
```java
import java.util.Comparator;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Data> set = new TreeSet<>(new DataComparator());
set.add(new Data("key1", "value1"));
set.add(new Data("key2", "value2"));
set.add(new Data("key1", "value3"));
set.add(new Data("key2", "value4"));
set.add(new Data("key3", "value5"));
set.add(new Data("key3", "value6"));
for (Data data : set) {
System.out.println(data);
}
}
static class Data {
String key;
String value;
public Data(String key, String value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return "Data{" +
"key='" + key + '\'' +
", value='" + value + '\'' +
'}';
}
}
static class DataComparator implements Comparator<Data> {
@Override
public int compare(Data o1, Data o2) {
if (o1.key.equals(o2.key)) {
// 如果key相同,则保留最新的value
return 1;
} else {
// 否则按照key的自然顺序排序
return o1.key.compareTo(o2.key);
}
}
}
}
```
输出结果为:
```
Data{key='key1', value='value3'}
Data{key='key2', value='value4'}
Data{key='key3', value='value6'}
```
可以看到,重复的key被去重了,并且保留了最新的value。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)