Using Java 8 Stream to replace for loop and populate a Map

user9569944 :

In this java assignment we have a for loop that reads through a text file we use in this program, and we are supposed to replace it with a stream. Here is part of the program and what we are supposed to replace:

    import java.io.FileNotFoundException;
    import java.util.List;
    import java.util.Map;
    import java.util.TreeMap;


    public class FrequentWords {

    public static void main(String[] args) throws FileNotFoundException {

    String filename = "SophieSallyJack.txt";
    if (args.length == 1) {
        filename = args[0];
    }
    Map<String, Integer> wordFrequency = new TreeMap<>();

    List<String> incoming = Utilities.readAFile(filename);

    // TODO replace the following loop with a single statement using streams    
    // that populates wordFrequency         
    for (String word : incoming) {
        word = word.toLowerCase();
        if (!"".equals(word.trim())) {
            Integer cnt = wordFrequency.get(word);
            if (cnt == null) {
                wordFrequency.put(word, 1);
            } else {
                int icnt = cnt + 1;
                wordFrequency.put(word, icnt);
            }
        }
    }

I have tried this and I can't seem to figure out anything else:

incoming.stream()
        .collect(Collectors.toMap(word -> word, word -> 1, Integer::sum)).entrySet();
Shubhendu Pramanik :

Here's what you can try:

wordFrequency = incoming.stream()
               .map(String::toLowerCase).filter(word -> !word.trim().isEmpty())
               .collect(Collectors.toMap
                (word -> word, word -> 1, (a, b) -> a + b, TreeMap::new));

You missed the BinaryOperator that will merge values of the key already exists Collectors.toMap()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=68313&siteId=1