[Java] Check the number of occurrences of characters

table of contents

--Introduction --Premise ――What you want to achieve ――What I tried --Problem

Introduction

Suddenly, I want to study Map and List! !! I thought </ b>, so I thought about the issues and made it. I stumbled upon the roles of Map and List and conversion. Even if I searched online, I couldn't find any good results, so I've put together my own, so I'll write an article.

Premise

――What you want to achieve --Identification of the most frequently used string for n arbitrary string type inputs (n_1 n_2 n_3 ... ... n). ――What I tried --Implemented [key: input string, value: number of appearances] as Map <String, Integer> map = Map () ;. --Sort the map by [value] and retrieve the very first [key]!

--Problem --Map system [HashMap, LinkedHashMap, TreeMap] basically has no order of elements. --Like map [0], you cannot retrieve the value by index.

  • Solution --You can get the combination of map key and value by using Map.Entry class. --You can store Entry objects in List and sort by Entry value of List [i].

Implementation details

The contents implemented based on the solution are as follows.

CountMain.java



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class CountMain {

	public static void main(String[] args) {

		//Input detection
		Scanner sc = new Scanner(System.in);
		String count = sc.nextLine();
		String[] line = sc.nextLine().split(" ");

		//Map making
		Map<String, Integer> map = new HashMap<String, Integer>();
		for(int i=0; i<line.length; i++){
			if(!map.containsKey(line[i])){
				map.put(line[i], 1);
			} else {
				int tmp = map.get(line[i]);
				map.remove(line[i]);
				map.put(line[i], tmp+1);
			}
		}

		//Get map entry → store in list
		List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
		for (Map.Entry<String, Integer> entry : map.entrySet()){
				list.add(entry);
		}

		//Compare the value of entry in list → sort
		for (int i = 0; i < list.size(); i++){
			for (int j = list.size()-1; j > i; j--){
				if (list.get(j).getValue() > list.get(j-1).getValue()){
					Map.Entry<String, Integer> tmpEntry = list.get(j-1);
					list.set(j-1, list.get(j));
					list.set(j, tmpEntry);
				}
			}
		}
		
		System.out.print(list.get(0).getKey());
		try {
			int i = 1;
			while( list.get(i).getValue() == list.get(i-1).getValue() ){
				System.out.print(" " + list.get(i).getKey());
				i++;
			}
		} catch (IndexOutOfBoundsException e){
			return;
		} finally {
			System.out.println("");
			sc.close();
		}
	}
}

At the end

--Summary ――It is important to be aware of the role of each class --Map throws a function to List when an associative array or an ordered array is needed ――Because I couldn't do this, I didn't understand when I first tried to sort the Map.

  • Future tasks --The sort in the list is done by human-powered bubble sort, but it seems that Collection.sort () can be used. --Something like Comparator <> seems to be useful. --Reference link below
    • https://www.sejuku.net/blog/16176
    • http://lovedvoraklayout.hatenablog.com/entry/java-map-value-sort-2
    • https://teratail.com/questions/117328

Recommended Posts

[Java] Check the number of occurrences of characters
Command to check the number and status of Java threads
[Java] Delete the specified number of characters from the end of StringBuilder
Check the contents of the Java certificate store
Count the number of occurrences of a string in Ruby
[Java] Check the JDK version of the built war file
Check the behavior of Java Intrinsic Locks with bpftrace
Set the maximum number of characters in UITextField in RxSwift
Count the number of digits after the decimal point in Java
[Java] Delete the elements of List
[Rails] Check the contents of the object
[Java version] The story of serialization
Check the version of Cent OS
Check the migration status of rails
The origin of Java lambda expressions
How to check for the contents of a java fixed-length string
Get the result of POST in Java
Check the contents of params with pry
Examine the memory usage of Java elements
[Java] Get the day of the specific day of the week
Compare the elements of an array (Java)
How to determine the number of parallels
[day: 5] I summarized the basics of Java
What are the updated features of java 13
Easily measure the size of Java Objects
Looking back on the basics of Java
Output of the book "Introduction to Java"
About the number of threads of Completable Future
The story of writing Java in Emacs
Check the version of the standard Web software.
[Java] [Spring] Test the behavior of the logger
Check the operation of the interface through threads
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
How to find the total number of pages when paging in Java
Check the domain by checking the MX record of the email address with java
[Java] Check if the character string is composed only of blanks (= Blank)
Check the version of the JDK installed and the version of the JDK enabled
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
JAVA: jar, aar, view the contents of the file
Check the options set for the running Java process
java (random number)
[Android] [Java] Manage the state of CheckBox of ListView
[Java] Number of connections required when nesting transactions
About the description order of Java system properties
About the idea of anonymous classes in Java
The order of Java method modifiers is fixed
[Java] Access the signed URL of s3 (signed version 2)
The story of learning Java in the first programming
Measure the size of a folder in Java
[Java] Get the length of the surrogate pair string
[Java] The confusing part of String and StringBuilder
[Note] Java: Measures the speed of string concatenation
I compared the characteristics of Java and .NET
Feel the passage of time even in Java
Let's check the feel of Spring Boot + Swagger 2.0
Calculate the similarity score of strings with JAVA
Try the free version of Progate [Java II]
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
[Java / Kotlin] Resize considering the orientation of the image
[Java] Judgment by entering characters in the terminal