Home > Java > javaTutorial > body text

Traversal methods of Java collections Set, List, and Map

高洛峰
Release: 2017-01-22 15:14:39
Original
1351 people have browsed it

The examples in this article describe the traversal methods of Java collections Set, List, and Map, and share them with you for your reference.

The 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);
     
    //Set的第一种遍历方式:利用Iterator
    Iterator<String> it1 = set.iterator();
    for (String ss : set) {
      System.out.println(ss);
    }
    //Set的第一种遍历方式:利用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);
     
    //List的第一种遍历方式:因为list有顺序,利用size()和get()方法获取
    for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i));
    }
    //List的第二种遍历方式:利用Iterator
    Iterator<String> it = list.iterator();
    while (it.hasNext()) {
      System.out.println(it.next());
    }
    //List的第三种遍历方式:利用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());
    //Map的第一种遍历方式:先获得key,再获得值value
    Set<String> sett = map.keySet();
    for (String s : sett) {
      System.out.println(s+":"+map.get(s));
    }
    //Map的第二种遍历方式:获得键值对
    for (Map.Entry<String, String> entry : map.entrySet()) {
      System.out.println(entry.getKey()+" : "+entry.getValue());
    }
  }
}
Copy after login

For more articles related to the traversal methods of Java collection Set, List, and Map, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!