Java Reference
In-Depth Information
16
17
// sort values in ascending order with streams
18
System.out.printf( "Sorted values: %s%n" ,
19
Arrays.stream(values)
.sorted()
.collect(Collectors.toList())
20
21
);
22
23
// values greater than 4
24
List<Integer> greaterThan4 =
Arrays.stream(values)
.filter(value -> value > 4 )
.collect(Collectors.toList());
25
26
27
28
System.out.printf( "Values greater than 4: %s%n" , greaterThan4);
29
30
// filter values greater than 4 then sort the results
31
System.out.printf( "Sorted values greater than 4: %s%n" ,
32
Arrays.stream(values)
.filter(value -> value > 4 )
.sorted()
.collect(Collectors.toList())
33
34
35
);
36
37
// greaterThan4 List sorted with streams
38
System.out.printf(
39
"Values greater than 4 (ascending with streams): %s%n" ,
40
greaterThan4.stream()
.sorted()
.collect(Collectors.toList())
41
42
);
43
}
44
} // end class ArraysAndStreams
Original values: [2, 9, 5, 0, 3, 7, 1, 4, 8, 6]
Sorted values: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Values greater than 4: [9, 5, 7, 8, 6]
Sorted values greater than 4: [5, 6, 7, 8, 9]
Values greater than 4 (ascending with streams): [5, 6, 7, 8, 9]
Fig. 17.6 | Demonstrating lambdas and streams with an array of Integer s. (Part 2 of 2.)
17.4.1 Creating a Stream<Integer>
When you pass an array of objects to class Arrays 's static method stream , the method
returns a Stream of the appropriate type—e.g., line 19 produces a Stream<Integer> from
an Integer array. Interface Stream (package java.util.stream ) is a generic interface for
performing stream operations on any non-primitive type. The types of objects that are pro-
cessed are determined by the Stream 's source.
Class Arrays also provides overloaded versions of method stream for creating Int-
Stream s, LongStream s and DoubleStream s from entire int , long and double arrays or
from ranges of elements in the arrays. The specialized IntStream , LongStream and Dou-
bleStream classes provide various methods for common operations on numerical streams,
as you learned in Section 17.3.
 
 
Search WWH ::




Custom Search