Java 8 foreach示例

时间:2020-02-23 14:34:52  来源:igfitidea点击:

在本教程中,我们将看到通过在Java 8中引入的地图和列表来迭代的改进方式。

在Java 8之前迭代HashMap的普通方式:

package org.igi.theitroad;
import java.util.HashMap;
 
public class HashMapIterationMap {
 
 public static void main(String args[])
 {
  //HashMap with Country as key and capital as value
  HashMap<String,String> countryCapitalMap=new HashMap<String,String>();
  countryCapitalMap.put("Netherlands","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");
 
  //Iterating Using keySet() and for each loop
  System.out.println("Iterating Using keySet() and for each loop");
  for (String countryKey:countryCapitalMap.keySet()) {
   System.out.println("Country:"+ countryKey +" and  Capital:"+countryCapitalMap.get(countryKey));
  }
  System.out.println("-----------------------------");
 }
 
}

在Java 8中迭代HashMap的改进方式:

package org.igi.theitroad;
import java.util.HashMap;
 
public class HashMapIterationMap {
 
 public static void main(String args[])
 {
  //HashMap with Country as key and capital as value
  HashMap<String,String> countryCapitalMap=new HashMap<String,String>();
  countryCapitalMap.put("Netherlands","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");
 
 
  //Iterating Using Java 8
  System.out.println("Iterating Using Java 8");
  System.out.println("-----------------------------");
  
  countryCapitalMap.forEach((k,v)->System.out.println("Country:" + k + " Capital : " + v));
  
  System.out.println("-----------------------------");
 }
 
}

迭代列表的普通方式:

package org.igi.theitroad;
import java.util.ArrayList;
 
public class IteratingArrayListMain {
 
 public static void main(String[] args) {
   ArrayList nameList=new ArrayList();//creating arraylist  
   nameList.add("igi");//adding object in arraylist  
   nameList.add("John");  
   nameList.add("Martin");  
   nameList.add("Adam"); 
   //Iterating list using foreach loop
    for(String name :nameList )
    {
     System.out.print(name+" ");
    }
 }
}

通过Java 8中的列表迭代:

package org.igi.theitroad;
import java.util.ArrayList;
 
public class IteratingArrayListMain {
 
 public static void main(String[] args) {
   ArrayList nameList=new ArrayList();//creating arraylist  
   nameList.add("igi");//adding object in arraylist  
   nameList.add("John");  
   nameList.add("Martin");  
   nameList.add("Adam"); 
   //Iterating list using foreach method
   nameList.forEach(n->System.out.print(n+" "));
 }
}