java、Map

来源:互联网 发布:淘宝怎么刷信用卡套现 编辑:程序博客网 时间:2024/06/14 22:00
//随机10个不重复的100以内的数字    ----》Set   0-100HashSet<Integer> set = new HashSet<Integer>();int i=0;while(i<10){    int num = new Random().nextInt(101);//[0,12)--->3    boolean flag = set.add(num);// 1,2,3    if (flag) {        i++;    }}System.out.println(set);
//key由Set维护关系  value有LinkedList去维护关系//HashMap<String,Object> map = new HashMap<String,Object>();//打印出来的键值对是无顺序的(不按照放入的顺序)、LinkedHashMap<String,Object> map = new LinkedHashMap<String,Object>();//打印出来的键值对是有顺序的(按照放入的顺序)、System.out.println(map.isEmpty());//falsemap.put("a","Jery2");//  --->entry(key,value)map.put(null,"Jery2");map.put(null,null);map.put("b","b1");map.put("c","c1");map.put("d","d1");map.put("e","e1");System.out.println(map.isEmpty());//trueSystem.out.println(map);//方法System.out.println(map.get("c"));//c1System.out.println(map.remove("d"));//d1System.out.println(map.containsKey("c1"));//truemap.clear();Collection<Object> valus =  map.values();//把值变成一个集合对象System.out.println(valus);////循环for( String key : map.keySet()){    System.out.print("Map的key为:"+key+"值为:"+map.get(key));}//entry循环for(Entry<String, Object>  m : map.entrySet()){    System.out.println(m.getKey()+":"+m.getValue());}//iterator+whileSet<String> keySet = map.keySet();Iterator<String>  iterator = keySet.iterator();while(iterator.hasNext()){    String key = iterator.next();    System.out.println(key+"  "+map.get(key));}//解决key排序问题TreeMap<Integer,Object> maps = new TreeMap<Integer,Object>(new Comparator<Integer>() {    @Override    public int compare(Integer o1, Integer o2) {        return o2.compareTo(o1);    }});    maps.put(6, "析析");    maps.put(5, "喜爱");    maps.put(4,"叶落征途");    maps.put(2,"叶落征途");    maps.put(9,"叶落征途");    maps.put(4,"叶落征途1111111");    maps.put(3, "Marlon");    for ( Map.Entry<Integer,Object> m: maps.entrySet()) {        System.out.println(m.getKey()+":"+m.getValue());    }//如果在Treemap里面想按照value进行排序,我们必须借助工具类Collections.sort(List,Comparator);TreeMap<String,Object> map2 = new TreeMap<String,Object>();    map2.put("a","a");    map2.put("b","cccccc");    map2.put("c","bbbbb");    map2.put("d","eeee");    map2.put("e","dd");ArrayList<Map.Entry<String,Object>> list = new ArrayList<Map.Entry<String,Object>>(map2.entrySet());    Collections.sort(list,new Comparator<Map.Entry<String,Object>>() {        @Override        public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {            return o2.getValue().toString().compareTo(o1.getValue().toString());            //自己实现的按照长度比            // Integer o11 = o1.getValue().toString().length();            // Integer o22 = o2.getValue().toString().length();            //return o22.compareTo(o11);        }        });    // for(Entry<String,String> m: map2.entrySet()){    //  System.out.println(m.getKey()+":"+m.getValue());    // }    for(Map.Entry<String,Object> l :list){        System.out.println(l.getKey()+":"+l.getValue());    }
原创粉丝点击