Java nima Java dasturlash tili


For loop orqali While loop + iterator


Download 1.25 Mb.
bet47/49
Sana20.01.2023
Hajmi1.25 Mb.
#1103409
1   ...   41   42   43   44   45   46   47   48   49
Bog'liq
2 5420273372074344755

For loop orqali

  • While loop + iterator

    Misol:


    import java.util.HashMap;
    import java.util.Map;
    import java.util.Iterator;
    public class Details
    {
    public static void main(String [] args)
    {
    HashMap hmap = new HashMap();
    //Adding elements to HashMap
    hmap.put(11, "AB");
    hmap.put(2, "CD");
    hmap.put(33, "EF");
    hmap.put(9, "GH");
    hmap.put(3, "IJ");

    //FOR LOOP


    System.out.println("For Loop:");
    for (Map.Entry me : hmap.entrySet()) {
    System.out.println("Key: "+me.getKey() + " & Value: " + me.getValue());
    }

    //WHILE LOOP & ITERATOR


    System.out.println("While Loop:");
    Iterator iterator = hmap.entrySet().iterator();
    while (iterator.hasNext()) {
    Map.Entry me2 = (Map.Entry) iterator.next();
    System.out.println("Key: "+me2.getKey() + " & Value: " + me2.getValue());
    }
    }
    }

    Ekranda:


    For Loop:
    Key: 2 & Value: CD
    Key: 3 & Value: IJ
    Key: 33 & Value: EF
    Key: 9 & Value: GH
    Key: 11 & Value: AB
    While Loop:
    Key: 2 & Value: CD
    Key: 3 & Value: IJ
    Key: 33 & Value: EF
    Key: 9 & Value: GH
    Key: 11 & Value: AB



    HashMap ni key orqali saralash

    Bu misolda HashMap ning key ni TreeMap dan foydalain saralash usulini ko’ramiz.


    import java.util.HashMap;
    import java.util.Map;
    import java.util.TreeMap;
    import java.util.Set;
    import java.util.Iterator;

    public class Details {


    public static void main(String[] args) {


    HashMap hmap = new HashMap();


    hmap.put(5, "A");
    hmap.put(11, "C");
    hmap.put(4, "Z");
    hmap.put(77, "Y");
    hmap.put(9, "P");
    hmap.put(66, "Q");
    hmap.put(0, "R");

    System.out.println("Saralashdan oldin:");


    Set set = hmap.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()) {
    Map.Entry me = (Map.Entry)iterator.next();
    System.out.print(me.getKey() + ": ");
    System.out.println(me.getValue());
    }
    Map map = new TreeMap(hmap);
    System.out.println("Saralashdan keyin:");
    Set set2 = map.entrySet();
    Iterator iterator2 = set2.iterator();
    while(iterator2.hasNext()) {
    Map.Entry me2 = (Map.Entry)iterator2.next();
    System.out.print(me2.getKey() + ": ");
    System.out.println(me2.getValue());
    }
    }
    }

    Download 1.25 Mb.

    Do'stlaringiz bilan baham:
  • 1   ...   41   42   43   44   45   46   47   48   49




    Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
    ma'muriyatiga murojaat qiling