# Java计算list元素的出现次数

2021年4月15日19:01:23 发表评论 1,254 次浏览

``````//Java program to count frequencies of elements
//using HashMap.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.*;

class GFG {
public static void countFrequencies(ArrayList<String> list)
{
//hashmap to store the frequency of element
Map<String, Integer> hm = new HashMap<String, Integer>();

for (String i : list) {
Integer j = hm.get(i);
hm.put(i, (j == null ) ? 1 : j + 1 );
}

//displaying the occurrence of elements in the arraylist
for (Map.Entry<String, Integer> val : hm.entrySet()) {
System.out.println( "Element " + val.getKey() + " "
+ "occurs"
+ ": " + val.getValue() + " times" );
}
}

public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
countFrequencies(list);
}
}``````

``````Element Geeks occurs: 2 times
Element for occurs: 1 times``````

``````//Java program to count frequencies of elements
//using HashSet and Collections.frequency.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.*;

class GFG {
public static void countFrequencies(ArrayList<String> list)
{

//hash set is created and elements of
//arraylist are insertd into it
Set<String> st = new HashSet<String>(list);
for (String s : st)
System.out.println(s + ": " + Collections.frequency(list, s));
}

public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
countFrequencies(list);
}
}``````

``````Geeks: 2
for: 1``````

``````//Java program to count frequencies of elements
//using HashMap.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.*;

class GFG {
public static void countFrequencies(ArrayList<String> list)
{

TreeMap<String, Integer> tmap = new TreeMap<String, Integer>();
for (String t : list) {
Integer c = tmap.get(t);
tmap.put(t, (c == null ) ? 1 : c + 1 );
}

for (Map.Entry m : tmap.entrySet())
System.out.println( "Frequency of " + m.getKey() + " is " + m.getValue());
}

public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
countFrequencies(list);
}
}``````

``````Frequency of Geeks is 2
Frequency of for is 1``````

• HashMap实现Map接口, 而TreeMap实现SortedMap Interface。
• HashMap使用散列, 而TreeMap使用红黑树(平衡BST)。所以基于HashMap的解决方案通常比基于TreeMap的解决方案要快得多.