List 集合的几种遍历方式

public class ListDemo {
    public static void main(String[] args) {
        List<Fruit> fruitList = new ArrayList<>();
        fruitList.add(new Fruit(1, "apple", "红色", 120.00));
        fruitList.add(new Fruit(2, "orange", "黄色", 140.00));
        fruitList.add(new Fruit(3, "guava", "灰色", 160.00));
        fruitList.add(new Fruit(4, "pear", "黄色", 180.00));
        fruitList.add(new Fruit(5, "mango", "黄色", 240.00));
        fruitList.add(new Fruit(6, "watermelon", "绿色", 260.00));

        // 遍历方式一
        // 对于 List 集合判空
        if (Objects.nonNull(fruitList) && !fruitList.isEmpty()) {
            for (int i = 0; i < fruitList.size(); i++) {
                System.out.println(i);
            }
        }

        // 遍历方式二
        if (Objects.nonNull(fruitList) && !fruitList.isEmpty()) {
            for (Fruit fruit : fruitList) {
                System.out.println(fruit);
            }
        }

        // 遍历方式三
        if (Objects.nonNull(fruitList) && !fruitList.isEmpty()) {
            ListIterator<Fruit> iterator = fruitList.listIterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        }

        // 遍历方式四
        if (Objects.nonNull(fruitList) && !fruitList.isEmpty()) {
            fruitList.forEach((x) -> System.out.println(x));
        }
    }
}