jdk1.8中的for循环
jdk1.8 从语法角度,感觉发生的变化还是蛮大的。在此记录一下。
for 循环
public static void main(String[] args) {
List<Animal> list = new ArrayList<Animal>();
list.add(new Animal("miamiao",2));
list.add(new Animal("wangwang",4));
//1.8 a为泛型中的对象
list.forEach(a ->{
System.out.println(a.getName());
});
//1.5 增强行for循环
for (Animal a : list) {
System.out.println(a.getName());
}
//普通循环
for(int i =0;i<list.size();i++){
System.out.println(list.get(i).getName());
}
}jdk1.8 新特性之 forEach 循环遍历
1、Foreach操作List
List<Integer> numbers = new ArrayList<>();
//no.1
for(Integer number : numbers){
System.out.println(number);
}
//no.2
for(int index=0,len=numbers.size();index<len;index++){
System.out.println(numbers.get(index));
}使用jdk1.8后,可这么写
//no.1
numbers.forEach((Integer integer) -> {
System.out.println(integer);
});
//no.2
numbers.forEach(integer -> {
System.out.println(integer);
});
//no.3
numbers.forEach(integer -> System.out.println(integer));
//no.4
numbers.forEach(System.out::println);
//no.5
numbers.forEach(new MyConsumer());2、 Foreach操作Map
原文地址:https://www.cnblogs.com/shanheyongmu/p/8351258.html