Traversal of collection elements in Java

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"});
  1. Use a standard for loop for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i); }

  2. 迭代器 Iterator<String> itor = list.iterator(); while (itor.hasNext()) { System.out.println(itor.next()); }

  3. 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

  4. 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); } });

  5. 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;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325024563&siteId=291194637