# Java: Frequency statistic code based on map implementation

Source: Internet
Author: User

Use the generic T to represent the class for which you want statistics, and you should effectively define equals () and Hascode () for that class.

Statistics () method for keyword statistics.

The Getallkeysstatistics () method returns the underlying map, which is all key-value pairs.

The Getallkeys () method returns the set of all the key components.

The Getkeystatistics () method returns a single statistic that determines the key.

The test example uses 10,000 random integer numbers (0~9) to count how often they are produced.

Package com.zj.col;

` import java.util.HashMap; import java.util.Map; import java.util.Random; public class Statistics 　　<T> { Private map<t, integer> m = new hashmap<t, integer> (); 　　　 public void statistics (T t) { Integer freq = m.get (t); M.put (t, freq = null 1:freq + 1); 　　} public void Getallkeysstatistics () { System.out.println (m); 　　 public void Getallkeys () { System.out.println (M.keyset ()); 　　 public int Getkeystatistics (T-t) { return m.get (t) = = null 0:m.get (t); 　　　 public static void Main (string[] args) { Random rand = new Random (); statistics<integer> s = new statistics<integer> (); for (int i = 0; I < 10000 i++) {//produce a number between 0 and 9: int r = Rand.nextin T (10); S.statistics (R); 　　　 } S.getallkeysstatistics (); S.getallkeys (); System.out.println ("Key-1:"+ s.getkeystatistics (-1)); System.out.println ("Key 0:" + s.getkeystatistics (0)); } } `

Results:

`{0=1038, 1=1014, 2=939, 3=987, 4=977, 5=974, 6=1036, 7=974, 8=1075, 9=986} [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Key -1:0 Key 0:1038`

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.