1. 程式人生 > >java 統計陣列中各元素出現的次數

java 統計陣列中各元素出現的次數


package javatest;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
 
public class NumOfEle {
 
    public static void main(String[] args) {
        String[] arr = new String[]{"aaa", "bbb", "ccc", "ddd", "ddd", "aaa"};
 
        Map<String, Integer> map = new HashMap<>();
 
        for (String str : arr) {
           Integer num = map.get(str);  
           map.put(str, num == null ? 1 : num + 1);
        }
        Set set = map.entrySet();
        Iterator it = set.iterator();
        System.out.println("方法一 :");
 
        while (it.hasNext()) {
            Map.Entry<String, Integer> entry = (Entry<String, Integer>) it.next();
            System.out.println("單詞 " + entry.getKey() + " 出現次數 : " + entry.getValue());
        }
 
        System.out.println("方法二 :");
 
        Iterator it01 = map.keySet().iterator();
        while (it01.hasNext()) {
            Object key = it01.next();
            System.out.println("單詞 " + key + " 出現次數 : " + map.get(key));
 
        }
    }
}
執行結果:
<pre name="code" class="java">方法一 :
單詞 aaa 出現次數 : 2
單詞 ccc 出現次數 : 1
單詞 bbb 出現次數 : 1
單詞 ddd 出現次數 : 2
方法二 :
單詞 aaa 出現次數 : 2
單詞 ccc 出現次數 : 1
單詞 bbb 出現次數 : 1
單詞 ddd 出現次數 : 2

 

 

java中list取前幾條資料

List newList = list.subList(start, end);

 start,end分別是第幾個到第幾個。