List,ArrayList,Map循环遍历

来源:互联网 发布:淘宝卖家押金怎么退 编辑:程序博客网 时间:2024/05/21 10:00

1.遍历List,ArrayList

public static void print(List<Integer> list) {      Iterator<Integer> itr = list.iterator();      while (itr.hasNext()) {          System.out.print(itr.next());          System.out.print(", ");      }      System.out.println();  }


List<Object> test = new ArrayList<String>();遍历:JDK1.5之前版本:Iterator iter = test.Iterator();while(iter.hasNext()){Object obj = iter.next();}JDK1.5版本以上:for(Object o:test){//对象o就是当前遍历到的对象System.out.println(o);}删除:在遍历list或者说在遍历集合过程中,执行了删除动作就会报错解决办法: 使用临时变量


2.遍历Map



public static void main(String[] args) {  Map<String, String> map = new HashMap<String, String>();  map.put("1", "value1");  map.put("2", "value2");  map.put("3", "value3");   //第一种:普遍使用,二次取值  System.out.println("通过Map.keySet遍历key和value:");  for (String key : map.keySet()) {   System.out.println("key= "+ key + " and value= " + map.get(key));  }   //第二种  System.out.println("通过Map.entrySet使用iterator遍历key和value:");  Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();  while (it.hasNext()) {   Map.Entry<String, String> entry = it.next();   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());  }                                                               //第三种:推荐,尤其是容量大时  System.out.println("通过Map.entrySet遍历key和value");  for (Map.Entry<String, String> entry : map.entrySet()) {   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());  }  //第四种  System.out.println("通过Map.values()遍历所有的value,但不能遍历key");  for (String v : map.values()) {   System.out.println("value= " + v);  } }



private static void visitMapByKey(Map map) {        Iterator keys = map.keySet().iterator();        while(keys.hasNext()){            Object key = keys.next();//key            Object value = map.get(key);//上面key对应的value        }    }



3.去重


public static ArrayList<String> removeDuplicateWithOrder(ArrayList<PocContactModel> contancts)    {        HashSet<PocContactModel> hashSet = new HashSet<PocContactModel>();        ArrayList<String> newlist = new ArrayList<String>();        for (Iterator<PocContactModel> iterator = contancts.iterator(); iterator.hasNext();)        {            PocContactModel element = (PocContactModel) iterator.next();            if (hashSet.add(element))            {                newlist.add(element.getSipUri());            }        }        contancts.clear();        return newlist;    }


原创粉丝点击