首页 > 代码库 > 集合例题

集合例题

字符出现次数

import java.util.HashMap;
import java.util.Map;

public class Practise {
     // 方法一
     public static void main(String[] args){
          Map m = new HashMap();
         int a = 0;
         int b = 0;
         int c = 0;
         int d = 0;
         String[] s={"aa","cc","dd","bb","cc","aa","cc"};
         for(int i=0;i<s.length;i++){
             if("aa".equals(s[i])){
                 a++;
             }else if("bb".equals(s[i])){
                 b++;
             }else if("cc".equals(s[i])){
                 c++;
             }else if("dd".equals(s[i])){
                 d++;
             }             
         }
         m.put("aa",a);
         m.put("bb",b);
         m.put("cc",c);
         m.put("dd",d);
         System.out.println(m);
     }



    
     //方法三
     public static void main2(String[] args){
          String[] ss={"aa","vv","rr","rr", "aa", "cc", "dd", "aa"};
     
          Map<String,Integer> map=new HashMap<String,Integer>();
     
          for(String s:ss){
               map.put(s,map.get(s)==null?1:map.get(s)+1);
          }
          System.out.println(map);
     }
     
}

随机分组

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Practise2 {
    public static void main(String[] args){
        List list =new ArrayList();
        Random r = new Random();
        
        int x=19;
        int group =3;
        
        for(int i=0;i<x;i++){
            list.add("no"+i);
        }
        
        for(int i=0;i<x;i++){
            if(i%group==0){
                System.out.println("第"+(i/group+1)+"组");    
            }
            int s=r.nextInt(x-i);
            if(list.size()==0){
                break;
            }
            System.out.println(list.remove(s));
        }
    }
}

 

集合例题