1+ package com .baeldung .forEach ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .Arrays ;
5+ import java .util .Iterator ;
6+ import java .util .List ;
7+ import java .util .function .Consumer ;
8+
9+ class ReverseList extends ArrayList <String > {
10+
11+ List <String > list = Arrays .asList ("A" , "B" , "C" , "D" );
12+
13+ Consumer <String > removeElement = s -> {
14+ System .out .println (s + " " + list .size ());
15+ if (s != null && s .equals ("A" )) {
16+ list .remove ("D" );
17+ }
18+ };
19+
20+ @ Override
21+ public Iterator <String > iterator () {
22+
23+ final int startIndex = this .size () - 1 ;
24+ final List <String > list = this ;
25+ return new Iterator <String >() {
26+
27+ int currentIndex = startIndex ;
28+
29+ @ Override
30+ public boolean hasNext () {
31+ return currentIndex >= 0 ;
32+ }
33+
34+ @ Override
35+ public String next () {
36+ String next = list .get (currentIndex );
37+ currentIndex --;
38+ return next ;
39+ }
40+
41+ @ Override
42+ public void remove () {
43+ throw new UnsupportedOperationException ();
44+ }
45+ };
46+ }
47+
48+ public void forEach (Consumer <? super String > action ) {
49+ for (String s : this ) {
50+ action .accept (s );
51+ }
52+ }
53+
54+ public void iterateParallel () {
55+ list .forEach (System .out ::print );
56+ System .out .print (" " );
57+ list .parallelStream ().forEach (System .out ::print );
58+ }
59+
60+ public void iterateReverse () {
61+ List <String > myList = new ReverseList ();
62+ myList .addAll (list );
63+ myList .forEach (System .out ::print );
64+ System .out .print (" " );
65+ myList .stream ().forEach (System .out ::print );
66+ }
67+
68+ public void removeInCollectionForEach () {
69+ list .forEach (removeElement );
70+ }
71+
72+ public void removeInStreamForEach () {
73+ list .stream ().forEach (removeElement );
74+ }
75+
76+ public static void main (String [] argv ) {
77+
78+ ReverseList collectionForEach = new ReverseList ();
79+ collectionForEach .iterateParallel ();
80+ collectionForEach .iterateReverse ();
81+ collectionForEach .removeInCollectionForEach ();
82+ collectionForEach .removeInStreamForEach ();
83+ }
84+ }
0 commit comments