java experiment 2.(4)(5)HashMap,TreeMap statistics character frequency

Posted by Billbonic on Tue, 09 Jul 2019 18:25:31 +0200

Requirements: Statistics of the frequency of each character in poem.txt using HashMap require that punctuation (;,..) not be included.,.;), whitespace' ', carriage return'\r', line break'\n', tab character'\t', number 0~9 (greater than'0'less than'9').

(1) Use for statements to find out the frequency of occurrences of "spring", "autumn", "day", "month", "mountain", "water", "night".

(2) Display words that occur 10 times or more by traversal.

The basic idea is to use HashMap to place the characters you own, update the character frequency, and Put into a new value to overwrite the original key-value pair.

Code:

import java.io.*;
import java.util.*;

public class MapTest1{
  public static void main(String[] args)throws IOException{
     char keys[] ={'spring','autumn','day','month','mountain','water','night'}; 
     String content = readFile(".\\poem.txt");
	 HashMap<Character, Integer> map = new HashMap<Character, Integer>();
	 for(int i = 0 ; i < content.length() ; i++)
	 {
		 Character temp = new Character(content.charAt(i));
		 if(isAsked(temp))
		 {
			 if(map.containsKey(temp))
			{
				int k = (map.get(temp));
				map.put(temp,k+1);
			}
			else 
			{
				map.put(temp,1);
			} 
		 } 
	 }
	 
	 Iterator<Character> it= map.keySet().iterator(); 
	 while (it.hasNext()) 
	{
		Character key = (Character) it.next();
		Integer value = map.get(key); // according to
		if (text1(key))
			 System.out.println(key + " " + value);
		 
	}
	
	 Iterator<Character> it2= map.keySet().iterator(); 
	 while (it2.hasNext()) 
	{
		Character key = (Character) it2.next();
		Integer value = map.get(key); // according to
		if (value > 10 ) 
			 System.out.println(key + " " + value);
		 
	}
  }
	static boolean isAsked(char c)
	{
		if( c == ';' || c == ',' ||c == '.' ||c == '. ' ||c == ',' ||c == ';' ||c == ' ' ||c == '\r' ||c == '\n' ||c == '\n' ||
		c == '\t') return false;
		if( c - '0' >= 0 &&  c - '0' <= 9) return false;
		return true;
	}
	
	static boolean text1(char c) //accodring to the ask of test1
	{
		if( c == 'spring' || c == 'autumn' ||c == 'day' ||c == 'month' ||c == 'mountain' ||c == 'water' ||c == 'night') return true;
		return false;
	}
	
  static String readFile(String fileName) throws IOException{
    	StringBuilder sb = new StringBuilder("");
        String s1="";
	int c1;
	FileInputStream f1= new FileInputStream(fileName);		
	InputStreamReader in = new InputStreamReader(f1, "UTF-8");

	while ((c1 = in.read()) != -1) {
	  sb.append((char) c1);
	}        
        return sb.toString();
  }
}

(5) Demand:

On the basis of the above question, TreeMap is required to sort all words by their occurrence frequency, and then display them from large to small by their occurrence frequency.* The occurrence frequency is used as the key, and the characters with the same frequency are separated by commas as the value.

Display:

Character 1 Number

Character 2 times...

* Requires String.split() and StringBuilder.insert() to be in reverse order (from small to large to large).Note to add the carriage return character'\n'.

Ideas for implementation:

Based on the above, we get a hashMap, which traverses HashMap in two layers, stores the keys of the same value in one stringBuilder, stores the corresponding frequency and the stringBuilder pair in one TreeMap, then adds a stringBuilder to each key-value pair in the TreeMap, divides them by split function with carriage return \nArrays, from large to small output.

One note: how map's key-value pairs are traversed:

for (Map.Entry<Integer, Integer> entry : map.entrySet())

Reference to - http://blog.csdn.net/tjcyjd/article/details/11111401

The implementation code is as follows:

import java.io.*;
import java.util.*;

public class MapTest2{
  public static void main(String[] args)throws IOException
  {
     String content = readFile(".\\poem.txt");
	 HashMap<Character, Integer> map = new HashMap<Character, Integer>();
	 for(int i = 0 ; i < content.length() ; i++)
	 {
		 Character temp = new Character(content.charAt(i));
		 if(isAsked(temp))
		 {
			 if(map.containsKey(temp))
			{
				int k = (map.get(temp));
				map.put(temp,k+1);
			}
			else 
			{
				map.put(temp,1);
			} 
		 } 
	 }
	 TreeMap<Integer,String> treeMap = new TreeMap<Integer,String>();
	for(Map.Entry<Character,Integer>entry:map.entrySet())
	{
		Integer value=entry.getValue();
		StringBuilder tmp=new StringBuilder("");
		 for(Map.Entry<Character, Integer>entry2:map.entrySet())
		 {
			if(value==entry2.getValue())
			{
				if(entry2.getKey()==' ') continue;
				tmp.append(entry2.getKey()+",");
			}
		}
		tmp.deleteCharAt(tmp.length()-1);//The last comma added
		treeMap.put(value, tmp.toString());
	}
	StringBuilder result=new StringBuilder("");
	 Iterator<Integer>it=treeMap.keySet().iterator();
	for(Map.Entry<Integer, String>entry:treeMap.entrySet()) //Put the result in a StringBuilder
	{
		String tmp="frequency:"+entry.getKey()+" char:"+entry.getValue();
		result.append(tmp+"\n");
		  
	}
	result.deleteCharAt(result.length()-1);//
	String[] datas=result.toString().split("\n");//Stringbuilder partitions into string arrays by newline characters
	for(int index=datas.length-1;index>=0;index--)
	{
		System.out.println(datas[index]);
	}
  }
	static boolean isAsked(char c)
	{
		if( c == ';' || c == ',' ||c == '.' ||c == '. ' ||c == ',' ||c == ';' ||c == ' ' ||c == '\r' ||c == '\n' ||
		c == '\t') return false;
		if( c - '0' >= 0 &&  c - '0' <= 9) return false;
		return true;
	}
	
	static boolean text1(char c) //accodring to the ask of test1
	{
		if( c == 'spring' || c == 'autumn' ||c == 'day' ||c == 'month' ||c == 'mountain' ||c == 'water' ||c == 'night') return true;
		return false;
	}
	
	static String readFile(String fileName) throws IOException
	{
    	StringBuilder sb = new StringBuilder("");
        String s1="";
		int c1;
		FileInputStream f1= new FileInputStream(fileName);		
		InputStreamReader in = new InputStreamReader(f1, "UTF-8");

		while ((c1 = in.read()) != -1) {
			sb.append((char) c1);
		}        
		return sb.toString();
	}
}

Topics: Java Spring less