Map和List的遍历方式

List

List strList = new ArrayList<>();
        strList.add("1");
        strList.add("2");
        strList.add("3");
        strList.add("4");
        strList.add("5");

        Iterator<String> iterator = strList.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            if (item.equals("3")) {
                iterator.remove();
            }
        }

        for (Object s : strList) {
            System.out.println(s.toString());
        }

ArrayList中经过执行System.arraycopy()方法以复制数组的方式来完成删除,插入,扩容等功能。apache

Map

public class TestMap {
         public static void main(String[] args) {
              Map<String, Object> map = new HashMap<String, Object>();
              map.put("aaa", 111);
              map.put("bbb", 222);
              map.put("ccc", 333);
              map.put("ddd", 444);
              //Map集合循环遍历方式一  
             System.out.println("第一种:经过Map.keySet()遍历key和value:");
            for(String key:map.keySet()){//keySet获取map集合key的集合  而后在遍历key便可
                String value = map.get(key).toString();//
                System.out.println("key:"+key+" vlaue:"+value);
            }

           //Map集合循环遍历二  经过迭代器的方式
           System.out.println("第二种:经过Map.entrySet使用iterator遍历key和value:");
           Iterator<Entry<String, Object>> it = map.entrySet().iterator();
           while(it.hasNext()){
                Entry<String, Object> entry = it.next();
                System.out.println("key:"+entry.getKey()+"  key:"+entry.getValue());
          }

         // Map集合循环遍历方式三 推荐,尤为是容量大时
        System.out.println("第三种:经过Map.entrySet遍历key和value");
        for (Map.Entry<String, Object> m : map.entrySet()) {
        System.out.println("key:" + m.getKey() + " value:" + m.getValue());
    }

         // 第四种:
         System.out.println("第四种:经过Map.values()遍历全部的value,但不能遍历key");
        for(Object m:map.values()){
          System.out.println(m);
        }
   }
}

将list按照某种方式拼接成字符串

public String listToString(List list, char separator) {
        return org.apache.commons.lang.StringUtils.join(list.toArray(), separator);
    }
相关文章
相关标签/搜索