A program that counts the number of words in a List

For some reason, I have constant access to the "Java word counting program" in my program every day. So, I posted the code posted on that blog I wrote it more than 10 years ago, but when I look at it now, I'm embarrassed that I don't use the generic type for List, and there are various immature parts.

Before.java


import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class WordCounterTable {
    private Map counterTable;
    
    public WordCounterTable(){
        this.counterTable = new HashMap();    
    }

    public void count(List list){
        for(Iterator ite = list.iterator();ite.hasNext();){
            Object target = ite.next();
            if(this.counterTable.get(target) == null){
                this.counterTable.put(target,new Integer(1));    
            }else{
                this.counterTable.put(target,
                new Integer(
                ((Integer)this.counterTable.get(target)).intValue()+1)
                );
            }
        }
    }
    
    public String printTableValue(){
        StringBuffer buf = new StringBuffer();
        for(Iterator ite = this.counterTable.keySet().iterator();ite.hasNext();){
            Object key = ite.next();
            buf.append("word:"+key+" count:"+this.counterTable.get(key)+"\n");
        }
        return buf.toString();
    }
}

So, I can't keep posting such an embarrassing program on my blog forever, so I rewrote it using the Stream function of Java8.

WordCount.java


package test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.function.Function;

public class WordCount {

	public static void main(String args[]){
		List<String> list = Arrays.asList("triple","evergreen","puisan","triple","puisan");
		Map<String,Integer> map = list.stream().collect(
				Collectors.groupingBy(
						//Set the List element as it is in the Map key
						Function.identity(),
						//Replace the List element with 1 for the Map value so that it counts
						Collectors.summingInt(s->1)) 
				);
		System.out.println(map);
	}
}
//{triple=2, puisan=2, evergreen=1}Is output to the console

The Stream function is convenient, isn't it? Compared to the previous light program, the logic is cleaner and it looks beautiful.

Recommended Posts

A program that counts the number of words in a List
Sample program that returns the hash value of a file in Java
Count the number of occurrences of a string in Ruby
Determine that the value is a multiple of 〇 in Ruby
Order of processing in the program
Find the number of days in a month with Kotlin
A program (Java) that outputs the sum of odd and even numbers in an array
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
Measure the size of a folder in Java
Creating a sample program using the problem of a database specialist in DDD Improvement 2
Get the path defined in Controller class of Spring boot as a list
Creating a sample program using the problem of a database specialist in DDD Improvement 1
Fall 2017 Security Specialist I checked the frequency of words that appeared in the morning 2
Get a list of classes in a Guava specific package
The objects in the List were references, right? Confirmation of
[Rails] Volume that displays favorites and a list of favorites
Set the maximum number of characters in UITextField in RxSwift
Extract a specific element from the list of objects
[Ruby] I want to make a program that displays today's day of the week!
Count the frequency of occurrence of words in a sentence by stream processing (Apache Apex)
Pursuing the mystery that the number of DB connections in Tomcat increases to only 8-A day of an OSS support engineer
A quick explanation of the five types of static in Java
List of devices that can be previewed in Swift UI
Check the dependency of a specific maven artifact in Coursier
A memo of the program that allows you to realize that the probability of dice rolling is about 1/6
Create a database of all the books that have been circulating in Japan in the last century
Aggregate the number of people every 10 years from List <Person>
I made a program in Java that solves the traveling salesman problem with a genetic algorithm
[Swift] When you want to know if the number of characters in a String matches a certain number ...
A list of complacency articles on language specifications that probably won't help you in programming directly
Generate a serial number with Hibernate (JPA) TableGenerator and store it in the Id of String.
I tried to summarize the words that I often see in docker-compose.yml
Get a proxy instance of the component itself in Spring Boot
The story that standard output also fatally changes the behavior of the program
Find out the list of fonts available in AWS Lambda + Java
A memo that containerizes the simple chat application of Node.js + socket.io
{The first consecutive 10-digit prime number in the value of e} .com
Cast an array of Strings to a List of Integers in Java
Examine the list of timezone IDs available in the Java ZoneId class
Get the public URL of a private Flickr file in Java
A story that struggled with the introduction of Web Apple Pay
The story that Tomcat suffered from a timeout error in Eclipse
Problem that the attribute of User model becomes nil in ActionMailer
How to output a list of strings in JSF as comma-separated strings
Let's create a TODO application in Java 5 Switch the display of TODO
Form that receives the value of the repeating item in Spring MVC
Let's make a custom_cop that points out the shaking of the name
A story that confirmed the profile of Yasuko Sawaguchi 36 years ago
[Java] Delete the elements of List
A list of rawValues for UITextContentType.
Sort a List of Java objects
This and that of the JDK
A memorandum of the FizzBuzz problem
List of members added in Java 9
Create a Servlet program in Eclipse
List of types added in Java 9
Number of digits in numeric item
Creating an ArrayList that allows you to throw in and retrieve the coordinates of a two-dimensional plane
A fix to prevent the increase in the number of DB connections in the custom authentication provider of the Cognos SDK sample
[Android] Develop a service that allows university students to check the operating status of buses circulating in the university.
[Spring Boot] List of validation rules that can be used in the property file for error messages