Several operations of traversing List
Introduction to the centralized operation method of traversing List in java. Create a new List as follows:
List<String> list = Arrays.asList(new String[]{"One", "Two","Three","Four","Five"});
-
Use a standard for loop for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i); }
-
迭代器 Iterator<String> itor = list.iterator(); while (itor.hasNext()) { System.out.println(itor.next()); }
-
foreach语法 for (String str : list) { System.out.println(str); }
At the bottom layer, this way of traversal uses the Iterator interface and completes the iteration through the hasNext() and next() methods, which is a syntactic sugar
-
Iterable.forEach(Java8)
Introduced in java8, if the Iterable interface is implemented, you can use list.forEach(new Consumer<String> { @Override public void accept(String name) { System.out.println(name); } });
-
lambda expression
It's the same as the above, except that the anonymous class list.forEach((final String name) -> System.out.println(name)) is replaced with a lambda expression;