distinct 报错 'java.util.stream.Stream' 中的 'distinct()' 无法应用于 '( )
时间: 2023-09-13 19:06:29 浏览: 134
如果报错 `'java.util.stream.Stream' 中的 'distinct()' 无法应用于 '( )'`,这是因为`distinct()`方法需要在Stream中找到一个合适的key来去重,而你的代码中没有指定key。
如果你想对对象进行去重,需要在对象中重写`equals()`和`hashCode()`方法。例如,如果你想根据`ShenTongMain`对象的`id`属性进行去重,可以重写`equals()`和`hashCode()`方法来比较`id`属性的值,代码如下:
```java
public class ShenTongMain {
private int id;
// other fields and methods
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ShenTongMain that = (ShenTongMain) o;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
```
然后,你可以使用以下代码来对两个List进行合并并去重:
```java
List<ShenTongMain> mergedList = Stream.concat(listOne.stream(), listTwo.stream())
.distinct()
.collect(Collectors.toList());
```
注意,`distinct()`方法需要在正确实现了`equals()`和`hashCode()`方法的情况下才能正常工作。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)