com.seavus.wordcountermaven.WordCounter.java Source code

Java tutorial

Introduction

Here is the source code for com.seavus.wordcountermaven.WordCounter.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seavus.wordcountermaven;

import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author George
 */
public class WordCounter {

    /**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException {
        InputStream fileStream = WordCounter.class.getClassLoader().getResourceAsStream("test.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));

        Map<String, Integer> wordMap = new HashMap<>();
        String line;

        boolean tokenFound = false;
        try {
            while ((line = br.readLine()) != null) {
                String[] tokens = line.trim().split("\\s+"); //trims surrounding whitespaces and splits lines into tokens
                for (String token : tokens) {
                    for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
                        if (StringUtils.equalsIgnoreCase(token, entry.getKey())) {
                            wordMap.put(entry.getKey(), (wordMap.get(entry.getKey()) + 1));
                            tokenFound = true;
                        }
                    }
                    if (!token.equals("") && !tokenFound) {
                        wordMap.put(token.toLowerCase(), 1);
                    }
                    tokenFound = false;
                }
            }
            br.close();
        } catch (IOException ex) {
            Logger.getLogger(WordCounter.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("string : " + "frequency\r\n" + "-------------------");
        //prints out each unique word (i.e. case-insensitive string token) and its frequency to the console
        for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

    }

}