JDK1.8新特性——使用新的方式遍歷集合

JDK1.8新特性——使用新的方式遍歷集合

摘要:本文主要學習了在JDK1.8中新增的遍歷集合的方式。學習

遍歷List

方法:ui

1 default void forEach(Consumer<? super T> action) {
2     Objects.requireNonNull(action);
3     for (T t : this) {
4         action.accept(t);
5     }
6 }

實例:this

1 public static void main(String[] args) {
2     List<String> list = new ArrayList<String>();
3     list.add("張三");
4     list.add("李四");
5     list.add("王五");
6     list.add("趙六");
7     list.forEach(e -> System.out.println(e));
8 }

遍歷Set

方法:spa

1 default void forEach(Consumer<? super T> action) {
2     Objects.requireNonNull(action);
3     for (T t : this) {
4         action.accept(t);
5     }
6 }

實例:code

1 public static void main(String[] args) {
2     Set<String> set = new HashSet<String>();
3     set.add("張三");
4     set.add("李四");
5     set.add("王五");
6     set.add("趙六");
7     set.forEach(e -> System.out.println(e));
8 }

遍歷Map

方法:blog

 1 default void forEach(BiConsumer<? super K, ? super V> action) {
 2     Objects.requireNonNull(action);
 3     for (Map.Entry<K, V> entry : entrySet()) {
 4         K k;
 5         V v;
 6         try {
 7             k = entry.getKey();
 8             v = entry.getValue();
 9         } catch(IllegalStateException ise) {
10             // this usually means the entry is no longer in the map.
11             throw new ConcurrentModificationException(ise);
12         }
13         action.accept(k, v);
14     }
15 }

實例:get

1 public static void main(String[] args) {
2     Map<Integer, String> map = new HashMap<Integer, String>();
3     map.put(101, "張三");
4     map.put(102, "李四");
5     map.put(103, "王五");
6     map.put(104, "趙六");
7     map.forEach((key, value) -> System.out.println(key+"->"+value));
8 }
相關文章
相關標籤/搜索