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;
}