Java 17 Recipes


-14. Filtering Data Before and After a Condition


Download 3.2 Mb.
Pdf ko'rish
bet45/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   41   42   43   44   45   46   47   48   ...   245
Bog'liq
Java 17 Recipes

2-14. Filtering Data Before and After a Condition 
with Streams
 Problem
You wish to utilize streams for effective manipulation of your collections. While doing so, 
you wish to filter those streams before and/or after a specified condition occurs. In the 
end, you want to retrieve all data within the collection before a given predicate condition 
is met. You also wish to retrieve all data within the collection after a given predicate 
condition is met.
 Solution
Utilize the new Java takeWhile() and dropWhile() constructs with your stream. 
Suppose we have the following collection of data, and we wish to retrieve all the 
elements before the element containing the word Java.
List myLangs = Arrays.asList("Jython is great","Groovy is awesome",
"Scala is functional", "JRuby is productive","Java is 
streamlined","","Kotlin is interesting");
To retrieve all elements prior to the element containing the “Java” string, we could 
use the takeWhile() construct, as follows.
Chapter 2 enhanCements from Java 9 through Java 17 


73
Stream.of("Jython is great","Groovy is awesome","Scala is functional",
"JRuby is productive","Java is streamlined","","Kotlin is 
interesting")
.takeWhile(s -> !s.contains("Java"))
.forEach(System.out::println);
Let’s suppose that we wish to retrieve all elements that occur after the element 
containing the “Java” string. We could use the dropWhile() construct, as follows.
Stream.of("Jython is great","Groovy is awesome","Scala is functional",
"JRuby is productive","Java is streamlined","","Kotlin is 
interesting")
.dropWhile(s -> !s.contains("Java"))
.forEach(System.out::println);
The following is the main class.
public static void main(String[] args){
List myLangs = Arrays.asList("Jython is great","Groovy 
is awesome","Scala is functional","JRuby is productive","Java is 
streamlined","","Kotlin is interesting");
System.out.println("Collection Data: " + myLangs);
takeWhileExample();
dropWhileExample();
}
The following is the output.
Collection Data: [Jython is great, Groovy is awesome, Scala is functional
JRuby is productive, Java is streamlined, , Kotlin is interesting]
takeWhileExample:
Jython is great
Groovy is awesome
Scala is functional
JRuby is productive
dropWhileExample:
Java is streamlined
Kotlin is interesting
Chapter 2 enhanCements from Java 9 through Java 17 


74

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   41   42   43   44   45   46   47   48   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling