Calculate the number of occurrences of repeated items in the Java List

Source: Internet
Author: User

Package com. qiyadeng. core; import java. util. arrayList; import java. util. collections; import java. util. hashMap; import java. util. hashSet; import java. util. list; import java. util. map; import java. util. set; import java. util. treeMap; public class CountDuplicatedList {public static void main (String [] args) {List list = new ArrayList (); list. add ("a"); list. add ("B"); list. add ("c"); list. add ("d"); list. add ("B "); List. add ("c"); list. add ("a"); list. add ("a"); list. add ("a"); System. out. println ("\ n Example 1-calculate the number of times 'A' appears"); System. out. println ("a:" + Collections. frequency (list, "a"); System. out. println ("\ n Example 2-calculate the number of times all objects appear"); Set uniqueSet = new HashSet (list); for (String temp: uniqueSet) {System. out. println (temp + ":" + Collections. frequency (list, temp);} System. out. println ("\ n Example 3-use Map to calculate the number of times an object appears"); Map map = New HashMap (); for (String temp: list) {Integer count = map. get (temp); map. put (temp, (count = null )? 1: count + 1);} printMap (map); System. out. println ("\ nMap sorting-sort by key"); Map treeMap = new TreeMap (map); printMap (treeMap);} public static void printMap (Map map Map) {for (Map. entry entry: map. entrySet () {System. out. println ("Key-value:" + entry. getKey () + "-" + entry. getValue () ;}} output result Example 1-calculate the number of occurrences of 'A' a: 4 EXAMPLE 2-calculate the number of occurrences of all objects d: 1b: 2c: 2a: 4 example 3-use Map to calculate the number of times an object appears Key-value: d-1Key-value: B-2Key-value: c-2Key-value: a-4Map sort-Sort key-value by Key: a-4Key-value: B-2Key-value: c-2Key-value: d-1

Contact Us

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.