java8 stream取某个属性并去重
时间: 2024-02-06 10:41:11 浏览: 21
可以通过如下代码实现:
```
List<MyObject> list = Arrays.asList(new MyObject("A"), new MyObject("B"), new MyObject("A"));
List<String> distinctNames = list.stream()
.map(MyObject::getName)
.distinct()
.collect(Collectors.toList());
```
其中,`MyObject` 为包含一个名字属性的类。`map` 方法将流中的每个对象映射为其名字属性,`distinct` 方法去重,最终通过 `collect` 方法转换为列表。
相关问题
java stream根据某个属性去重
可以使用Java 8 Stream的distinct()方法对某个属性进行去重。比如,对于一个包含对象的流,可以使用以下代码对属性name进行去重:
list.stream().filter(distinctByKey(Employee::getName)).collect(Collectors.toList());
其中distinctByKey()方法可以自己实现,代码如下:
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
stream流根据某个属性去重
在Java中,可以使用Stream流根据某个属性去重。下面是一个示例代码:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", 25));
personList.add(new Person("Bob", 30));
personList.add(new Person("Alice", 25));
personList.add(new Person("Charlie", 35));
List<Person> distinctPersons = personList.stream()
.collect(Collectors.toMap(Person::getName, person -> person, (p1, p2) -> p1))
.values()
.stream()
.collect(Collectors.toList());
distinctPersons.forEach(person -> System.out.println(person.getName() + " - " + person.getAge()));
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
上述代码中,我们创建了一个Person类,包含name和age属性。我们使用Stream流对personList进行去重操作,根据name属性进行去重。具体步骤如下:
1. 使用`collect(Collectors.toMap(...))`将List转换为Map,其中key为name属性,value为对应的Person对象。
2. 使用`.values()`获取Map中的所有value,即去重后的Person对象集合。
3. 使用`collect(Collectors.toList())`将去重后的Person对象集合转换为List。
4. 最后,使用`forEach`遍历去重后的Person对象集合,并输出name和age属性。
运行上述代码,输出结果为:
```
Alice - 25
Bob - 30
Charlie - 35
```