Person person = personList.get(0);中person.toString里的值为null
时间: 2023-12-07 13:06:01 浏览: 21
如果在 `Person` 类的 `toString()` 方法中返回了 `null`,那么在调用 `person.toString()` 方法时会返回 `null`。你可以检查一下 `Person` 类的 `toString()` 方法的实现,看看是否有可能返回 `null` 值。此外,也需要确认 `personList` 不是空的,并且 `personList` 的第一个元素不是 `null`。如果 `personList.get(0)` 返回了 `null`,那么在调用 `person.toString()` 方法时也会返回 `null`。
相关问题
Map<Integer, Person> personMap = personList.stream().collect(Collectors.toMap(Person::getId, Function.identity())); 去重
如果你想根据 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`。
Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);还能怎么写
这段代码可以使用简化的方式重写,如下所示:
```
int sumSalary = personList.stream().mapToInt(Person::getSalary).sum();
```
这里使用了`mapToInt`方法将`Person`对象的薪资映射为一个`IntStream`,然后使用`sum`方法将其求和。这种方式比使用`reduce`方法更加简洁明了。