Map<Integer, Person> personMap = personList.stream().collect(Collectors.toMap(Person::getId, Function.identity())); 去重
时间: 2024-02-06 10:09:18 浏览: 25
如果你想根据 Person 对象的 id 字段进行去重,可以在 toMap 方法中增加一个 mergeFunction 参数,用于合并重复键的值。例如:
```
Map<Integer, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Function.identity(), (p1, p2) -> p1));
```
上面的代码中,当出现重复的键(即两个 Person 对象的 id 相同时),我们选择保留第一个对象的值,即 p1。如果你想保留最后一个对象的值,可以修改为 `(p1, p2) -> p2`。
相关问题
stream().collect(Collectors.toMap
`stream().collect(Collectors.toMap())`是Java 8中的一个方法,它可以将一个流转换为一个Map对象。该方法需要两个参数:一个是用于生成Map键的函数,另一个是用于生成Map值的函数。下面是一个例子:
假设我们有一个Person类,其中包含id和name两个属性。我们想将一个Person列表转换为一个Map,其中id是键,name是值。可以使用以下代码:
```java
List<Person> personList = new ArrayList<>();
personList.add(new Person(1, "Alice"));
personList.add(new Person(2, "Bob"));
personList.add(new Person(3, "Charlie"));
Map<Integer, String> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(personMap);
```
输出结果为:`{1=Alice, 2=Bob, 3=Charlie}`
在上面的代码中,`Person::getId`和`Person::getName`是方法引用,用于生成Map的键和值。`toMap()`方法将这些键值对收集到一个Map中。
java8中 Collectors.toMap 详解
Java 8中的Collectors.toMap方法可以将Stream中的元素转换为一个Map对象。该方法有三个参数:keyMapper,valueMapper和mergeFunction。其中,keyMapper用于将Stream中的元素转换为Map的key,valueMapper用于将Stream中的元素转换为Map的value,mergeFunction用于处理当key重复时的冲突情况。
下面是一个例子,假设我们有一个List对象,其中包含多个Person对象,每个Person对象都有一个唯一的id属性和一个name属性。我们可以使用Collectors.toMap方法将List转换为一个以id为key,以Person对象为value的Map对象:
```java
List<Person> personList = new ArrayList<>();
// 假设我们已经将多个Person对象添加到了personList中
Map<Integer, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Function.identity()));
```
在上面的例子中,Person::getId表示将Person对象的id属性作为Map的key,Function.identity()表示将Person对象本身作为Map的value。如果我们想要将Person对象的name属性作为Map的value,可以这样写:
```java
Map<Integer, String> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
```
如果我们的List中有重复的id,那么上面的代码将会抛出IllegalStateException异常。为了避免这种情况,我们可以使用mergeFunction参数来处理冲突。例如,如果我们想要将重复的id的Person对象合并为一个List,可以这样写:
```java
Map<Integer, List<Person>> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Collections::singletonList, (list1, list2) -> {
List<Person> resultList = new ArrayList<>(list1);
resultList.addAll(list2);
return resultList;
}));
```
在上面的代码中,Collections::singletonList表示将Person对象转换为只包含一个元素的List,mergeFunction参数则表示将两个List合并为一个List。