Traversal methods for Java collections Set List and Map

  • 2020-04-01 03:27:48
  • OfStack

The example of this article describes the Java Set, List, Map traversal methods, to share with you for your reference.

Specific methods are as follows:


package com.shellway.javase;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.junit.Test;

public class TestCollection {
  
  public static void print(Collection<? extends Object> c){
    Iterator<? extends Object> it = c.iterator();
    while (it.hasNext()) {
      Object object = (Object) it.next();
      System.out.println(object);
    }
  }
  
  @Test
  public void demo1(){
    Set<String> set = new HashSet<String>();
    set.add("AAA");
    set.add("BBB");
    set.add("CCC");
    print(set);
    
    //The first method of traversing a Set: using the Iterator
    Iterator<String> it1 = set.iterator();
    for (String ss : set) {
      System.out.println(ss);
    }
    //The first traversal of a Set: use foreach
    for (String sss : set) {
      System.out.println(sss);
    }
    
    List<String> list = new ArrayList<String>();
    list.add("DDDDD");
    list.add("EEEEE");
    list.add("FFFFF");
    print(list);
    
    //The first way of traversing a List: because the List is in order, get it using the size() and get() methods
    for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i));
    }
    //The second way to iterate over a List is with the Iterator
    Iterator<String> it = list.iterator();
    while (it.hasNext()) {
      System.out.println(it.next());
    }
    //The third way of traversing a List: using foreach
    for (String s2 : list) {
      System.out.println(s2);
    }
    
    Map<String,String> map = new TreeMap<String, String>();
    map.put("Jerry", "10000");
    map.put("shellway", "20000");
    map.put("Kizi", "30000");
    print(map.entrySet());
    //The first way to iterate over a Map is to get the key and then the value
    Set<String> sett = map.keySet();
    for (String s : sett) {
      System.out.println(s+":"+map.get(s));
    }
    //The second way of traversing a Map is to get a key-value pair
    for (Map.Entry<String, String> entry : map.entrySet()) {
      System.out.println(entry.getKey()+" : "+entry.getValue());
    }
  }
}

Generics are used here for type safety checking and traversal of collection objects.

I hope this article will be helpful to your Java programming study.


Related articles: