有个List<A>,A里有List<B>,B里有List<C>,用java代码去重
时间: 2024-03-22 22:37:13 浏览: 19
可以使用Java8的Stream API和flatMap()方法来对嵌套的三层List集合进行去重,具体实现如下:
```java
List<A> listA = new ArrayList<>();
// ... 初始化listA
List<C> uniqueListC = listA.stream()
.flatMap(a -> a.getListB().stream())
.flatMap(b -> b.getListC().stream())
.distinct()
.collect(Collectors.toList());
```
其中,getListB()表示从A对象中获取嵌套的List<B>集合,getListC()表示从B对象中获取嵌套的List<C>集合,distinct()表示去除重复元素,collect(Collectors.toList())表示将去重后的元素重新组合成一个List返回。
需要注意的是,如果A、B、C类没有重写equals()和hashCode()方法,去重操作可能无法正常执行。此时,需要在A、B、C类中重写equals()和hashCode()方法,以确保去重操作的正确性。
相关问题
java实现List<List<Integer>>去重
可以使用HashSet来实现List<List<Integer>>中的去重。具体的实现步骤如下:
1. 定义一个HashSet用于存储不重复的List<List<Integer>>,定义一个List<List<Integer>>用于存储去重后的结果。
2. 遍历List<List<Integer>>,对于每个子List<Integer>,将其转换为一个HashSet<Integer>,然后再将该HashSet<Integer>转换为List<Integer>。
3. 将转换后的List<Integer>加入到一个新的List<List<Integer>>中,如果该List<List<Integer>>已存在于HashSet中,则不加入;否则将该List<List<Integer>>加入HashSet和结果List<List<Integer>>中。
4. 返回结果List<List<Integer>>即可。
下面是示例代码:
```java
public static List<List<Integer>> removeDuplicate(List<List<Integer>> list) {
Set<List<Integer>> set = new HashSet<>();
List<List<Integer>> result = new ArrayList<>();
for (List<Integer> subList : list) {
Set<Integer> subSet = new HashSet<>(subList);
List<Integer> subListNoDup = new ArrayList<>(subSet);
if (set.add(subListNoDup)) {
result.add(subListNoDup);
}
}
return result;
}
```
java 两个List<Long> 去重
在Java中,对于两个List<Long>,可以采用以下两种方式进行去重:
1. 通过HashSet去重
对于两个List<Long>,可以将它们分别转换为HashSet<Long>,再将这两个Set合并为一个Set,最后再将Set转换为List<Long>,即可去重。具体实现如下:
```java
List<Long> list1 = new ArrayList<Long>();
// 添加元素到list1中
List<Long> list2 = new ArrayList<Long>();
// 添加元素到list2中
Set<Long> set = new HashSet<Long>(list1);
set.addAll(list2);
List<Long> resultList = new ArrayList<Long>(set);
```
2. 通过Java 8 Stream API去重
对于两个List<Long>,可以先将这两个List合并为一个List,再通过Java 8 Stream API进行去重操作,具体实现如下:
```java
List<Long> list1 = new ArrayList<Long>();
// 添加元素到list1中
List<Long> list2 = new ArrayList<Long>();
// 添加元素到list2中
List<Long> resultList = Stream.of(list1, list2)
.flatMap(x -> x.stream())
.distinct()
.collect(Collectors.toList());
```
以上两种方式均可以实现对两个List<Long>的去重操作,使用哪种方式取决于具体的需求和实现场景。