[英]How to get unique values with frequency from List<String[]> in Java?
I want to get unique values from a List<String[]>
and store them in a new list (or HashMap<String, Integer>
where String
is the unique value and Integer
is its number of occurrences in the List<String[]>
. How can I extract the unique values?我想从List<String[]>
获取唯一值并将它们存储在一个新列表中(或HashMap<String, Integer>
其中String
是唯一值, Integer
是它在List<String[]>
中的出现次数. 如何提取唯一值?
You can use Collectors.groupingBy
您可以使用Collectors.groupingBy
Map<String, Long> map = abc.stream()
.flatMap(Arrays::stream)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
If you are using Java 8 or above it's pretty easy.如果您使用的是 Java 8 或更高版本,这很容易。 (Slight correction using the other answer) (使用其他答案进行轻微修正)
List<String[]> abc = new ArrayList<>();
String[] string1 = {"123", "567"};
String[] string2 = {"123", "456"};
abc.add(string1);
abc.add(string2);
List<String> newList = abc.stream()
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
Map<String, Long> hashMap = abc.stream()
.flatMap(Arrays::stream)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.