list用map统计重复元素
时间: 2023-07-27 18:11:34 浏览: 42
可以使用Java 8中的Stream API和Collectors.toMap()方法来实现:
```java
List<String> list = Arrays.asList("apple", "banana", "orange", "apple", "orange", "grape");
Map<String, Long> result = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result);
```
输出结果为:
```
{orange=2, grape=1, banana=1, apple=2}
```
其中,`Collectors.groupingBy(Function.identity(), Collectors.counting())`将List中的元素按照自身分组,然后统计每个分组中元素的个数,最终返回一个Map。其中,`Function.identity()`表示使用元素自身作为分组依据。
相关问题
java 统计list有多少个重复的元素
要统计一个Java的List中重复元素的个数,可以使用HashMap来实现。HashMap是一种基于键值对的存储结构,通过键值对可以快速查找数据。
首先,需要遍历List中的所有元素,将元素作为HashMap中的Key,出现次数作为Value存储。遍历结束后,再次遍历HashMap,统计Value大于1的元素个数即为List中的重复元素个数。
以下是代码示例:
```java
import java.util.*;
public class CountDuplicateElements {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 2, 3, 4, 5, 5, 5);
Map<Integer, Integer> map = new HashMap<>();
// 遍历List,将元素作为Key,出现次数作为Value存储到HashMap中
for (Integer element : list) {
if (map.containsKey(element)) {
map.put(element, map.get(element) + 1);
} else {
map.put(element, 1);
}
}
// 统计HashMap中Value大于1的元素个数
int duplicateCount = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
duplicateCount++;
}
}
System.out.println("List中重复元素的个数为:" + duplicateCount);
}
}
```
输出结果为:
```
List中重复元素的个数为:3
```
以上是一种基本且常见的用法,还有其他实现方式,可以根据具体需求选择合适的方法。
list重复数据转map空指针
可以使用Java 8的Stream API将重复数据转换为Map。具体实现如下:
```
List<String> list = Arrays.asList("a", "b", "c", "a", "b");
Map<String, Long> map = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map);
```
输出结果为:{a=2, b=2, c=1}
其中,groupingBy方法根据元素的值进行分组,counting方法统计每个分组中元素的数量。
如果list中存在null元素,可以使用下面的代码:
```
List<String> list = Arrays.asList("a", "b", "c", "a", "b", null);
Map<String, Long> map = list.stream()
.filter(Objects::nonNull)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map);
```
输出结果为:{a=2, b=2, c=1}