I am creating a Word Comparison class and it will count the occurrences of words as well. (This is Java)
This was my original method:
/**
* @param map The map of words to search
* @param num The number of words you want printed
* @return list of words
*/
public static List<String> findMaxOccurrence(Map<String, Integer> map, int num) {
List<WordComparable> l = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet())
l.add(new WordComparable(entry.getKey(), entry.getValue()));
My IDE suggested that the loop and list assignment could be replaced with a "collect call": "stream api calls"
In which it generated this code:
List<WordComparable> l =
map.entrySet().stream()
.map(entry -> new WordComparable
(entry.getKey(), entry.getValue())).collect(Collectors.toList());
I am kinda confused on how the lambda math works. If my memory serves correctly, the -> is the for each loop, but the other calls are completely confusing.
My IDE can also expand the code into these two snippets:
List<WordComparable> l =
map.entrySet().stream()
.map(entry -> {
return new WordComparable
(entry.getKey(), entry.getValue());
}).collect(Collectors.toList());
And
List<WordComparable> l =
map.entrySet().stream()
.map(new Function<Map.Entry<String, Integer>, WordComparable>() {
@Override
public WordComparable apply(Map.Entry<String, Integer> entry) {
return new WordComparable
(entry.getKey(), entry.getValue());
}
}).collect(Collectors.toList());
Any light-shedding would be awesome.