Java Reference
In-Depth Information
case, we use streams to sort the values in greaterThan4 , collect the results into a new
List<Integers> and display the sorted values.
17.5 Stream<String> Manipulations
[This section demonstrates how lambdas and streams can be used to simplify programming
tasks that you learned in Chapter 14, Strings, Characters and Regular Expressions.]
Figure 17.7 performs some of the same stream operations you learned in Sections 17.3-
17.4 but on a Stream<String> . In addition, we demonstrate case-insensitive sorting and
sorting in descending order. Throughout this example, we use the String array strings
(lines 11-12) that's initialized with color names—some with an initial uppercase letter.
Line 15 displays the contents of strings before we perform any stream processing.
1
// Fig. 17.7: ArraysAndStreams2.java
2
// Demonstrating lambdas and streams with an array of Strings.
3
import java.util.Arrays;
4
import java.util.Comparator;
5
6
7
import java.util.stream.Collectors;
public class ArraysAndStreams2
8
{
9
public static void main(String[] args)
10
{
11
String[] strings =
12
{ "Red" , "orange" , "Yellow" , "green" , "Blue" , "indigo" , "Violet" };
13
14
// display original strings
15
System.out.printf( "Original strings: %s%n" , Arrays.asList(strings));
16
17
// strings in uppercase
18
System.out.printf( "strings in uppercase: %s%n" ,
19
Arrays.stream(strings)
20
.map(String::toUpperCase)
21
.collect(Collectors.toList()));
22
23
// strings less than "n" (case insensitive) sorted ascending
24
System.out.printf( "strings greater than m sorted ascending: %s%n" ,
25
Arrays.stream(strings)
26
.filter(s -> s.compareToIgnoreCase( "n" ) < 0 )
27
.sorted( String.CASE_INSENSITIVE_ORDER )
28
.collect(Collectors.toList()));
29
30
// strings less than "n" (case insensitive) sorted descending
31
System.out.printf( "strings greater than m sorted descending: %s%n" ,
32
Arrays.stream(strings)
33
.filter(s -> s.compareToIgnoreCase( "n" ) < 0 )
34
.sorted( String.CASE_INSENSITIVE_ORDER .reversed())
35
.collect(Collectors.toList()));
36
}
37
} // end class ArraysAndStreams2
Fig. 17.7 | Demonstrating lambdas and streams with an array of String s. (Part 1 of 2.)
 
Search WWH ::




Custom Search