【发布时间】:2019-10-10 23:21:31
【问题描述】:
我想从List<String[]> 中获取唯一值并将它们存储在一个新列表中(或HashMap<String, Integer>,其中String 是唯一值,Integer 是它在List<String[]> 中的出现次数。如何我可以提取唯一值吗?
【问题讨论】:
我想从List<String[]> 中获取唯一值并将它们存储在一个新列表中(或HashMap<String, Integer>,其中String 是唯一值,Integer 是它在List<String[]> 中的出现次数。如何我可以提取唯一值吗?
【问题讨论】:
您可以使用Collectors.groupingBy
Map<String, Long> map = abc.stream()
.flatMap(Arrays::stream)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
【讨论】:
如果您使用的是 Java 8 或更高版本,这很容易。 (使用其他答案稍作修正)
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()));
【讨论】: