zoukankan      html  css  js  c++  java
  • JDK1.8新特性——使用新的方式遍历集合

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

    摘要:本文主要学习了在JDK1.8中新增的遍历集合的方式。

    遍历List

    方法:

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

    实例:

    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

    方法:

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

    实例:

    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

    方法:

     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 }

    实例:

    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 }
  • 相关阅读:
    Ruby自学笔记(二)— Ruby的一些基础知识
    Ruby自学笔记(一)— 基本概况
    Tomcat基础教程(四)
    Excel导入
    构建API
    序列化
    图片上传(练习)
    发邮件
    发短信
    Excel表导出
  • 原文地址:https://www.cnblogs.com/shamao/p/11853056.html
Copyright © 2011-2022 走看看