我正在尝试计算List<List<String>>中每个元素的出现次数,并将结果存储在Map<String,Long>中。
Map<String, Long> map = new HashMap<>();
for(List<String> l : data) {
for(int i = 0; i < l.size(); i++) {
String myString = l.get(i);
long count = data.stream().filter(d -> myString.equals(d)).count();
map.put(myString, count);
}
}我的代码返回0作为每个键的值。有没有办法解决这个问题?谢谢。
发布于 2019-10-13 06:53:54
试试这个:
List<List<String>> listOflists = new ArrayList<>();
//Initialize your list here
Map<String, Long> map = listOflists.stream().flatMap(Collection::stream)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));发布于 2019-10-13 06:53:00
您正在流式传输data,这是一个List<List<String>>。这意味着流的每个元素都有List<String>类型。然后,在filter的lambda中,您将尝试查看myString (类型为String)是否等于d (类型为List<String>)。这永远不会是真的,使所有元素的count都等于0。
您需要做的是在data.stream()返回的流上调用flatMap,函数参数为List::stream (或Collection::stream)。这样做的目的是将List<String>流转换为String流,然后可以对其调用filter方法。
https://stackoverflow.com/questions/58359008
复制相似问题