Java – Duyệt/lặp Trên HashMap | HOW TO CODE

Có 2 cách để lặp 1 map: Giả sử có HashMap sau

HashMap<String, String> mapDatas = new HashMap<>(); mapDatas.put("first", “A”); mapDatas.put("second", "B");
  • Lấy ra tập key rồi duyệt dựa trên nó
for (String key : mapDatas.keySet()) { System.out.println("key: " + key + " value: " + mapDatas.get(key)); } Set<String> keySet = mapDatas.keySet(); Iterator<String> keySetIterator = keySet.iterator(); while (keySetIterator.hasNext()) { String key = keySetIterator.next(); System.out.println("key: " + key + " value: " + mapDatas.get(key)); }
  • Sử dụng EntrySet và vòng lặp for hoặc iterator
Set<Map.Entry<String, String>> entrySet = mapDatas.entrySet(); for (Entry entry : entrySet) { System.out.println("key: " + entry.getKey() + " value: " + entry.getValue()); } Iterator<Entry<String, String>> entrySetIterator = entrySet.iterator(); while (entrySetIterator.hasNext()) { Entry<String, String> entry = entrySetIterator.next(); System.out.println("key: " + entry .getKey() + " value: " + entry.get(key)); } Like Loading... Post navigation Java – Kiểm tra Array có phần tử giống nhau hay không? Java – Sự khác nhau giữa HashMap và HashTable

Leave a comment Cancel reply

Δ

Search Recent Posts
  • test
  • Java – NIO – Channel
  • Java – NIO – Buffer
  • Java – NIO – Giới thiệu
  • Java – Singleton
Bài viết
  • November 2015 (44)
Categories
  • Game (1)
  • Java (42)
  • Uncategorized (1)
TagsCollection Concurrency Design Pattern Game I/O Java NIO String Thread Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use. To find out more, including how to control cookies, see here: Cookie Policy
  • Comment
  • Reblog
  • Subscribe Subscribed
    • HOW TO CODE
    • Sign me up
    • Already have a WordPress.com account? Log in now.
    • HOW TO CODE
    • Customize
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Copy shortlink
    • Report this content
    • View post in Reader
    • Manage subscriptions
    • Collapse this bar
%d Design a site like this with WordPress.comGet started

Từ khóa » Duyệt Map Trong Java