zoukankan      html  css  js  c++  java
  • jdk1.8 foreach

    lambda 表达式效率非常低,测试代码可以看到大概3~5倍的差距

    遍历Map的方式有很多,通常场景下我们需要的是遍历Map中的Key和Value,那么推荐使用的:

    1. public static void main(String[] args)

    2. {

    3.    HashMaphm = new HashMap();

    4.    hm.put(“111”, “222”);

    5.    Set<Map.Entry<String, String>> entrySet = hm.entrySet();

    6.    Iterator<Map.Entry<String, String>> iter = entrySet.iterator();

    7.    while (iter.hasNext())

    8.    {

    9.         Map.Entry<String, String> entry = iter.next();

    10.         System.out.println(entry.getKey() + " " + entry.getValue());

    11.    }

    12. }

    如果你只是想遍历一下这个Map的key值,那用”SetkeySet = hm.keySet();”会比较合适一些。

    如果使用jdk1.8 

    In Java 8, you can loop a Map with forEach + lambda expression.

    Map<String, Integer> items = new HashMap<>();
    items.put("A", 10);
    items.put("B", 20);
    items.put("C", 30);
    items.put("D", 40);
    items.put("E", 50);
    items.put("F", 60);
    
    items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
    
    items.forEach((k,v)->{
    	System.out.println("Item : " + k + " Count : " + v);
    	if("E".equals(k)){
    		System.out.println("Hello E");
    	}
    });
     -----------List遍历
    List<String> items = new ArrayList<>();
    items.add("A");
    items.add("B");
    items.add("C");
    items.add("D");
    items.add("E");
    
    for(String item : items){
    	System.out.println(item);
    }

    2.2 In Java 8, you can loop a List with forEach + lambda expression or method reference.

    List<String> items = new ArrayList<>();
    items.add("A");
    items.add("B");
    items.add("C");
    items.add("D");
    items.add("E");
    
    //lambda
    //Output : A,B,C,D,E
    items.forEach(item->System.out.println(item));
    
    //Output : C
    items.forEach(item->{
    	if("C".equals(item)){
    		System.out.println(item);
    	}
    });
    
    //method reference
    //Output : A,B,C,D,E
    items.forEach(System.out::println);
    
    //Stream and filter
    //Output : B
    items.stream()
    	.filter(s->s.contains("B"))
    	.forEach(System.out::println);
  • 相关阅读:
    透视表提取不反复记录(1)-出现值
    ORA-38760: This database instance failed to turn on flashback database
    Android蓝牙串口程序开发
    指尖上的电商---(5)schema.xml配置具体解释
    iOS-UIImage imageWithContentsOfFile 和 imageName 对照
    JSON-RPC轻量级远程调用协议介绍及使用
    POJ 2296 Map Labeler(2-sat)
    接口測试-HAR
    [Leetcode]Combination Sum II
    MarkDown、Vim双剑合璧
  • 原文地址:https://www.cnblogs.com/-xuzhankun/p/8059659.html
Copyright © 2011-2022 走看看