java List去除空元素
时间: 2023-04-01 21:01:55 浏览: 66
可以使用Java中的removeAll方法来去除List中的空元素。具体实现可以参考以下代码:
List<String> list = new ArrayList<>();
list.add("hello");
list.add("");
list.add("world");
list.add(null);
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));
System.out.println(list);
输出结果为:[hello, world]
相关问题
java 两个list去除重复元素
可以使用Java8中的Stream API来实现两个List去除重复元素的操作,具体代码如下:
```java
List<String> list1 = Arrays.asList("A", "B", "C", "D");
List<String> list2 = Arrays.asList("B", "C", "E", "F");
List<String> result = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
System.out.println(result);
```
输出结果为:`[A, B, C, D, E, F]`
这里使用了`Stream.concat`方法将两个List合并为一个Stream,再使用`distinct`方法去重,最后使用`collect`方法将结果收集为List。
java 兩個list 去除重複元素
可以使用Java 8的Stream API来实现两个List去除重复元素。
假设有两个List,分别为list1和list2,我们可以通过以下代码去除重复元素:
```
List<String> distinctList = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
```
上述代码使用了Stream.concat()方法将两个List合并成一个Stream对象,再调用distinct()方法去除重复元素,最后使用collect()方法将Stream对象转化为List对象。
如果需要去除重复元素后仅保留list1中的元素,可以使用以下代码:
```
List<String> distinctList = Stream.concat(list1.stream(), list2.stream())
.filter(list1::contains)
.collect(Collectors.toList());
```
上述代码使用了filter()方法过滤掉list2中的元素,最终得到仅包含list1中元素的List对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)