遍历HashMap的5种方法

 Map<Integer,Double> mixerRemain=new HashMap<>();
        for(int i=0;i<data.size();i++) {
            JSONObject object = (JSONObject) data.get(i);
            RemainCur newRemain = (RemainCur) JSONObject.toBean(object, Remain.class);
          
            //后搅拌车 余料方量
            if(mixerRemain.containsKey(newRemain.getMixerEid())){
                mixerRemain.put(newRemain.getMixerEid(),mixerRemain.get(newRemain.getMixerEid())+newRemain.getShiftQty().doubleValue());
            }else{
                mixerRemain.put(newRemain.getMixerEid(),newRemain.getShiftQty().doubleValue());
            }
        }

1.使用迭代器遍历HashMap EntrySet


        Iterator<Map.Entry<Integer, Double>> iterator = mixerRemain.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer, Double> entry = iterator.next();
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }

2.使用迭代器遍历HashMap KeySet

 Iterator<Integer> iterator = mixerRemain.keySet().iterator();
        while (iterator.hasNext()){
            Integer key = iterator.next();
            System.out.println(key);
            System.out.println(mixerRemain.get(key));
        }

3.使用For-each循环迭代HashMap

for (Map.Entry<Integer,Double> map:mixerRemain.entrySet()) {
               System.out.println(map.getKey());
                System.out.println(map.getValue());
        }

4.使用lambda表达式遍历HashMap`

 mixerRemain.forEach((key,vlaue) ->{
                System.out.println(key);
                System.out.println(vlaue);
            }
        );

5.使用Stream API 遍历HashMap

  mixerRemain.entrySet().stream().forEach((integerDoubleEntry -> {
                    System.out.println(integerDoubleEntry.getKey());
                    System.out.println(integerDoubleEntry.getValue());
                })
        );

注:使用过程中发现第4和5不支持return返回值

你可能感兴趣的:(Java)