Map 遍历方法(包括java8)

Map 遍历主要有两种KeySet EntrySet

第一种:KeySet

       TreeMapmap=new TreeMap<>();
        map.put("1","lj");
        map.put("3","lll");
        map.put("3","eee");
        map.put("4","ewwwwwww");
        //Collection values = map.values();
        Set strings = map.keySet();
        Iterator iterator = strings.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            System.out.println(next+":"+map.get(next));
        }

第二种:EntrySet

        String key="";
        String value="";
        Map map=new HashMap<>();
        map.put("1","lj");
        map.put("2","lll");
        map.put("3","eee");
        map.put("4","ewwwwwww");
        Set> entries = map.entrySet();
        Iterator> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry next = iterator.next();
            key= next.getKey();
            value= next.getValue();
            System.out.println(key+":"+value);
        }
    }

第三种:java8

     //根据value 排序后展示map
      Mapmapp=new HashedMap();
      mapp.put(1,2);
      mapp.put(2,4);
      mapp.put(3,7);
      mapp.put(4,9);
      Comparator> entryComparator = Map.Entry.comparingByValue();
      Consumer> kKeyStreamingChannel = (x) -> {
          System.out.println(x);
      };
      mapp.entrySet().stream().sorted(entryComparator).forEach(kKeyStreamingChannel);
     
      输出:1=2 2=4 3=7  4=9

      //普通循环遍历:
      Consumer> kKeyStreamingChannel = (x) -> {
          System.out.println(x);
      };
      mapp.entrySet().stream().forEach(kKeyStreamingChannel);

你可能感兴趣的:(java)