java中的迭代方法

1.使用迭代器rem

Iterator中有三個方法:hasNext() /next() /remove()get

ArrayList list = new ArrayList();//省略賦值過程
Iterator iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
HashMap<String,Object> map = new HashMap<>();//省略賦值過程
Iterator<Map.Entry<String,Object>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
       System.out.println(iterator.next());
}

ListIterator有九個方法:add(E e) /hasNext() /hasPrevious() /next() /nextIndex() /previous() /previousIndex() /remove() /set(E e):it

ArrayList list = new ArrayList();//省略賦值過程
ListIterator listIt = list.listIterator();
while (listIt.hasNext()) {
    if ("abc".equals(listIt.next())) {
        listIt.add("efg");
    }
}

2.使用forEach語句io

ArrayList list = new ArrayList();//省略賦值過程
list.forEach(value->{
    System.out.println(value+"123");
});
Map<String,Object> map = new HashMap<>();//省略賦值過程
map.forEach((key,value)->{
    System.out.println(key+":"+value);
});
String[] str = new String[10];//省略賦值過程
Arrays.stream(str).forEach(value->{
    System.out.println(value);
});

3.使用加強forstream

List<String> lists = new ArrayList<>();//省略賦值過程
for (String list : lists){
    System.out.println(list);
}
Map<String,Object> map = new HashMap<>();//省略賦值過程
for (Map.Entry<String,Object> entry : map.entrySet() ){
    System.out.println(entry.getKey()+":"+entry.getValue());
}
//或者
for (String key : map.keySet()){
    System.out.println(key+":"+map.get(key));
}
相關文章
相關標籤/搜索