Java-da xarita orqali takrorlashning turli usullari

Java-da xaritani ko'rib chiqish. Ushbu xabarda biz Java-dagi xarita orqali iteratsiya qilishning to'rt xil usulini ko'rib chiqamiz. Java 8-dan boshlab, biz xarita bo'ylab aylanish uchun forEach usulidan va iterator sinfidan foydalanishimiz mumkin.



Xaritadagi yozuvlarni qanday o'zgartirish kerak (kalitlar va qiymatlar)

Map map = new HashMap(); for (Map.Entry entry : map.entrySet()) {
System.out.println('Key = ' + entry.getKey() + ', Value = ' + entry.getValue()); }


Faqat xarita kalitlarini qanday qilib takrorlash mumkin

Map map = new HashMap(); for (Integer key : map.keySet()) {
System.out.println('Key = ' + key); }


Faqat xarita qiymatlarini qanday o'zgartirish mumkin?

for (Integer value : map.values()) {
System.out.println('Value = ' + value); }

Bog'liq:



Iterator-dan foydalanish

Generics-dan foydalanish:


Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println('Key = ' + entry.getKey() + ', Value = ' + entry.getValue()); }

Generics holda:

Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println('Key = ' + key + ', Value = ' + value); }


Kalitlarni takrorlash va qiymatlarni qidirish

Map map = new HashMap(); for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println('Key = ' + key + ', Value = ' + value); }


Java 8 ForEach-dan foydalanish

Map items = new HashMap();
items.put('key 1', 1);
items.put('key 2', 2);
items.put('key 3', 3);
items.forEach((k,v)->System.out.println('Item : ' + k + ' Count : ' + v));