Helen Grey :
I am trying to count the number of occurrences of every element in a List<List<String>>
, and store the results in a 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);
}
}
My code returns zero as value for every key. Is there a way to fix it? Thank you.
Villat :
Try with this:
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()));
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=309765&siteId=1