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

jdk1.8中的for循环问题记录

jdk1.8中的for循环问题记录

原文地址:https://www.cnblogs.com/shanheyongmu/p/8351258.html

相关文章:

  • 2022-12-23
  • 2021-09-25
  • 2021-09-16
  • 2021-07-22
  • 2021-07-11
  • 2023-03-20
  • 2021-08-24
  • 2021-12-06
猜你喜欢
  • 2021-08-18
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-12-23
  • 2021-12-21
相关资源
相似解决方案