java lombda list对象根据某一属性去重
时间: 2024-02-05 07:08:39 浏览: 165
以下是Java中使用lambda表达式和Stream API对List对象根据某一属性进行去重的方法:
1. 使用lambda表达式和HashSet进行去重:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.collect(Collectors.toCollection(() -> new HashSet<>(person -> person.getName())));
```
2. 使用lambda表达式和LinkedHashSet进行去重,保持原有顺序:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.collect(Collectors.toCollection(() -> new LinkedHashSet<>(person -> person.getName())));
```
3. 使用Stream API的distinct方法进行去重:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.distinct()
.collect(Collectors.toList());
```
4. 使用Stream API的collect方法和Collectors.groupingBy进行去重:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(person -> person.getName())),
ArrayList::new));
```
5. 使用Stream API的collect方法和Collectors.toMap进行去重:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.collect(Collectors.collectingAndThen(
Collectors.toMap(Person::getName, Function.identity(), (existing, replacement) -> existing),
map -> new ArrayList<>(map.values())));
```
6. 使用Stream API的collect方法和Collectors.toMap进行去重,保持原有顺序:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.collect(Collectors.collectingAndThen(
Collectors.toMap(Person::getName, Function.identity(), (existing, replacement) -> existing, LinkedHashMap::new),
map -> new ArrayList<>(map.values())));
```
7. 使用Stream API的collect方法和Collectors.collectingAndThen进行去重:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))),
ArrayList::new));
```
8. 使用Stream API的collect方法和Collectors.collectingAndThen进行去重,保持原有顺序:
```java
List<Person> list = new ArrayList<>();
// 假设Person类有一个name属性
List<Person> distinctList = list.stream()
.filter(person -> person.getName() != null)
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))),
ArrayList::new));
```
阅读全文
相关推荐
















