Java中map的九种遍历方法-创新互联

Java中map的九种遍历方法

1. 通过for和map.entrySet()遍历

创新互联公司专注于石狮网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供石狮营销型网站建设,石狮网站制作、石狮网页设计、石狮网站官网定制、小程序定制开发服务,打造石狮网络公司原创品牌,更为您提供石狮网站排名全网营销落地服务。
public void ergodicMap(Mapmap){for(Map.Entryentry : map.entrySet()){System.out.println("Key:"+entry.getKey()+",Value:"+entry.getValue());
    }
}

2. 通过for,iterator和map.entrySet()遍历

public void ergodicMap(Mapmap){for(Iterator>entries = map.entrySet().iterator();entries.hasNext();){Map.Entryentry = entries.next();
        System.out.println("Key:"+entry.getKey()+",Value:"+entry.getValue());
    }
}

3. 通过while,Iterator和map.entrySet()遍历

public void ergodicMap(Mapmap){Iterator>entries = map.entrySet().iterator();
    while(entries.hasNext()){ Map.Entryentry = entries.next();
        System.out.println("Key:"+entry.getKey()+",Value:"+entry.getValue());
    }
}

4. 通过for和map.keySet()遍历

public void ergodicMap(Mapmap){for(Integer key : map.keySet()){System.out.println("Key:"+key+",Value:"+map.getKey());
    }
}

5. 通过for,Iterator和map.keySet()遍历

public void ergodicMap(Mapmap){for(Iteratorkey = map.keySet().iterator(); key.hasNext();){System.out.println("Key:"+key.next()+",Value:"+map.get(key.next()));
    }
}

6. 通过while,Iterator和map.keySet()遍历

public void ergodicMap(Mapmap){Iteratorkey = map.keySet().iterator();
    while(key.hasNext()){System.out.println("Key:"+key.next()+",Value:"+map.get(key.next()));
    }
}
java8的遍历方式

7. 通过map.forEach()遍历

JDK中的forEach方法,使用率比较高。

public void ergodicMap(Mapmap){map.forEach((key,value) ->{   System.out.println("Key:"+key+",Value:"+value);
    })
}

8. Stream遍历

public void ergodicMap(Mapmap){long sum = map.entrySet().stream().mapToLong(e ->e.getKey() + e.getValue)).sum();
    System.out.println(sum);
}

9. parallelStream遍历

public void ergodicMap(Mapmap){long sum = map.entrySet().parallelStream().mapToLong(e ->e.getKey() + e.getValue)).sum();
   System.out.println(sum);
}

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


文章题目:Java中map的九种遍历方法-创新互联
分享地址:http://lszwz.com/article/dsojes.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款