그만큼 각각() 의 방법 배열목록 ArrayList의 각 요소에 대해 특정 작업을 수행하는 데 사용됩니다. 이 메소드는 모든 요소가 메소드에 의해 처리되거나 예외가 발생할 때까지 ArrayList의 Iterable의 각 요소를 순회합니다. 메서드에 해당 순서가 지정된 경우 반복 순서대로 작업이 수행됩니다. Operation에서 발생한 예외는 호출자에게 전달됩니다.
재정의 클래스가 동시 수정 정책을 지정하지 않는 한 작업은 요소의 기본 소스를 수정할 수 없으므로 이 메서드의 동작이 지정되지 않았다고 말할 수 있습니다.
Java의 컬렉션에서 요소 검색.
통사론:
public void forEach(Consumer action)>
매개변수: 이 메서드는 매개변수를 사용합니다. 행동 각 요소에 대해 수행할 작업을 나타냅니다.
보고: 이 메서드는 아무것도 반환하지 않습니다.
예외: 지정된 작업이 null인 경우 이 메서드는 NullPointerException을 발생시킵니다.
아래 프로그램은 ArrayList의 forEach() 메서드를 보여줍니다.
프로그램 1: 숫자 목록이 포함된 ArrayList의 forEach() 메서드를 시연하는 프로그램입니다.
// Java Program Demonstrate forEach()> // method of ArrayList> > import> java.util.*;> public> class> GFG {> > > public> static> void> main(String[] args)> > {> > // create an ArrayList which going to> > // contains a list of Numbers> > ArrayList Numbers => new> ArrayList();> > > // Add Number to list> > Numbers.add(> 23> );> > Numbers.add(> 32> );> > Numbers.add(> 45> );> > Numbers.add(> 63> );> > > // forEach method of ArrayList and> > // print numbers> > Numbers.forEach((n) ->System.out.println(n));> > }> }> |
자바에서 난수 생성
>
>산출:
23 32 45 63>
프로그램 2: 학생 이름 목록이 포함된 ArrayList의 forEach() 메서드를 시연하는 프로그램입니다.
// Java Program Demonstrate forEach()> // method of ArrayList> > import> java.util.*;> public> class> GFG {> > > public> static> void> main(String[] args)> > {> > // create an ArrayList which going to> > // contains a list of Student names which is actually> > // string values> > ArrayList students => new> ArrayList();> > > // Add Strings to list> > // each string represents student name> > students.add(> 'Ram'> );> > students.add(> 'Mohan'> );> > students.add(> 'Sohan'> );> > students.add(> 'Rabi'> );> > > // print result> > System.out.println(> 'list of Students:'> );> > > // forEach method of ArrayList and> > // print student names> > students.forEach((n) ->인쇄(n));> > }> > > // printing student name> > public> static> void> print(String n)> > {> > System.out.println(> 'Student Name is '> + n);> > }> }> |
>
>산출:
무순_맵 C++
list of Students: Student Name is Ram Student Name is Mohan Student Name is Sohan Student Name is Rabi>