A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/java-tutorial/arraylist/arraylist_foreach.php below:

Website Navigation


Java ArrayList.forEach Method - w3resource

Java ArrayList.forEach() MethodLast update on August 19 2022 21:51:25 (UTC/GMT +8 hours) public void forEach(Consumer<? super E> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.

Package: java.util

Java Platform: Java SE 8

Syntax:

forEach(Consumer<? super E> action)

Parameters:

Name Description Type action The action to be performed for each element  

Return Value:
the element previously at the specified position

Example: ArrayList.forEach Method

The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly.

import java.util.*;
import java.util.function.*;

class MyConsumer<T> implements Consumer<T>{
 public void accept(T ctask){
  System.out.println("Processing Task " + ctask);
 }
}


import java.util.*;
import java.util.*;

import java.util.function.*;

class MyConsumer implements Consumer{

 public void accept(T ctask){

  System.out.println("Processing Task " + ctask);

 }

}

public class Main {

   public static void main(String[] args) 

   {

  ArrayList myList;

  MyConsumer mcons;

  myList = new ArrayList<>(50);

  mcons = new MyConsumer
         (); myList.add(100); myList.add(200); myList.add(300); myList.add(400); myList.forEach(mcons); } }

Output:

F:\java>javac test.java

F:\java>java test
Processing Task 100
Processing Task 200
Processing Task 300
Processing Task 400

Previous:subList Method
Next:spliterator


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4