栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 8 - forEach 来循环或迭代 Map、List、Set 、Stream

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 8 - forEach 来循环或迭代 Map、List、Set 、Stream

文章目录
      • 1. forEach 循环 Map
      • 2. forEach 循环 List
      • 3. forEach 和 Consumer 接口
      • 4. forEach 与 forEachOrdered

1. forEach 循环 Map

1.1 正常方式循环 Map

public class Foreach {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("A", 10);
        map.put("B", 20);
        map.put("C", 30);
        map.put("D", 40);
        map.put("E", 50);
        map.put("F", 60);

        for (Map.Entry entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue());
        }
    }
}

执行结果:

Key : A, Value : 10
Key : B, Value : 20
Key : C, Value : 30
Key : D, Value : 40
Key : E, Value : 50
Key : F, Value : 60

1.2 forEach 循环 Map

public class Foreach {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("A", 10);
        map.put("B", 20);
        map.put("C", 30);
        map.put("D", 40);
        map.put("E", 50);
        map.put("F", 60);

        // lambda
        map.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));
    }
}

执行结果:

Key : A, Value : 10
Key : B, Value : 20
Key : C, Value : 30
Key : D, Value : 40
Key : E, Value : 50
Key : F, Value : 60

1.3 对于Map 包含的键或值 null ,forEach 将打印 null。

public class Foreach {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("A", 10);
        map.put("B", 20);
        map.put(null, 30);
        map.put("D", null);
        map.put("E", 50);
        map.put("F", 60);

        // lambda
        map.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));
    }
}

执行结果:

Key : null, Value : 30
Key : A, Value : 10
Key : B, Value : 20
Key : D, Value : null
Key : E, Value : 50
Key : F, Value : 60

1.4 如果不想打印 key=null 的值,可以在 forEach 中指定

public class Foreach {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("A", 10);
        map.put("B", 20);
        map.put(null, 30);
        map.put("D", null);
        map.put("E", 50);
        map.put("F", 60);

        // lambda
        map.forEach(
                (k,v)->{
                    if(k!=null){
                        System.out.println("Key : " + k + ", Value : " + v);
                    }
                }
        );
    }
}

执行结果:

Key : A, Value : 10
Key : B, Value : 20
Key : D, Value : null
Key : E, Value : 50
Key : F, Value : 60

2. forEach 循环 List

2.1 正常方式循环列表

public class Foreach {
    public static void main(String[] args) {

        List list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");

        // normal loop
        for (String l : list) {
            System.out.println(l);
        }
    }
}

执行结果:

A
B
C
D
E

2.2 Java 8 中,可以使用 forEach 循环一个 List

public class Foreach {
    public static void main(String[] args) {

        List list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");

        list.forEach(s->{
            System.out.println(s);
        });

        // lambda
        list.forEach(System.out::println);
    }
}

执行结果:

A
B
C
D
E

2.3 过滤 List 中的 null 值

public class Foreach {
    public static void main(String[] args) {

        List list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add(null);
        list.add("D");
        list.add("E");

        list.stream()
                .filter(Objects::nonNull)
                .forEach(System.out::println);
    }
}

执行结果:

A
B
D
E

3. forEach 和 Consumer 接口

查看forEach方法签名,它接受一个功能接口 Consumer

public interface Iterable {

  default void forEach(Consumer action) {
      Objects.requireNonNull(action);
      for (T t : this) {
          action.accept(t);
      }
  }
  //..
}
public interface Stream extends BaseStream> {

  void forEach(Consumer action);
  //...

}

这个例子创建了一个Consumer将String打印成Hex格式的方法。

public class Foreach {
    public static void main(String[] args) {

        List list = Arrays.asList("abc", "java", "python");
        Stream stream = Stream.of("abc", "java", "python");
        
        // convert a String to a Hex
        Consumer printTextInHexConsumer = new Consumer() {
            @Override
            public void accept(String s) {
                StringBuilder stringBuilder = new StringBuilder();
                for (char c : s.toCharArray()) {
                    String hex = Integer.toHexString(c);
                    stringBuilder.append(hex);
                }
                System.out.println(stringBuilder.toString());
            }
        };

        // lambda:convert a String to a Hex
        Consumer printTextInHexConsumer1 = (String x)  -> {
            StringBuilder stringBuilder = new StringBuilder();
            for (char c : s.toCharArray()) {
                String hex = Integer.toHexString(c);
                stringBuilder.append(hex);
            }
            System.out.println(stringBuilder.toString());
        };

        // pass a Consumer
        list.forEach(printTextInHexConsumer);
        stream.forEach(printTextInHexConsumer);
    }
}
4. forEach 与 forEachOrdered

forEach不保证流的数据顺序,不管流是顺序的还是并行的。当以并行模式运行时,结果是显而易见的。

public class Foreach {
    public static void main(String[] args) {
        Stream s = Stream.of("a", "b", "c", "1", "2", "3");
        s.parallel().forEach(x -> System.out.println(x));
    }
}

输出结果:

1
3
2
b
c
a

forEachOrdered保证流的数据顺序;因此,它牺牲了并行性的好处。

public class Foreach {
    public static void main(String[] args) {
        Stream s = Stream.of("a", "b", "c", "1", "2", "3");
        // keep order, it is always a,b,c,1,2,3
        s.parallel().forEachOrdered(x -> System.out.println(x));
    }
}

a
b
c
1
2
3

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/981560.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号