Spaces:
Running
Running
map mapToInt mapToDouble collect
Browse files
Week 7: Enum, Generic Type, Streams, write to file, class diagram/11A. Useful Stream Operations+++
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The operation 'map' applies the SAME OPERATION to EACH ELEMENT of the stream.
|
| 2 |
+
Afterwards, the stream is formed from the results of the operations - 'map' can therefore change the type of the stream elements.
|
| 3 |
+
The operations 'mapToInt' and 'mapToDouble' are special versions of the map operation.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
For example, if we had a list of 'Teacher' objects and
|
| 7 |
+
wanted to count the number of teachers whose name is longer than 10 characters,
|
| 8 |
+
we could use a stream as follows:
|
| 9 |
+
|
| 10 |
+
// count returns a value of type long
|
| 11 |
+
long count = teachers.stream().map(teacher -> teacher.getName()).
|
| 12 |
+
filter(name -> name.length() > 10).count();
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
Another useful stream operation is 'collect'.
|
| 19 |
+
It allows you to 'FORM A COLLECTION FROM A STREAM' again.
|
| 20 |
+
|
| 21 |
+
So if we have a list of Teacher objects following the previous example,
|
| 22 |
+
and we want to create a list of the teachers' email addresses,
|
| 23 |
+
we can do so by combining the operations 'map' and 'collect':
|
| 24 |
+
|
| 25 |
+
ArrayList<String> emails = teachers.stream().map(teacher -> teacher.getEmail()).
|
| 26 |
+
collect(Collectors.toCollection(ArrayList::new));
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
Another example where we have a list of integers.
|
| 33 |
+
We want to create a new list that has only the negative elements from the original list.
|
| 34 |
+
|
| 35 |
+
Since the 'collect' operation only works on object type streams,
|
| 36 |
+
we change the stream from 'int' type to 'Integer' type with the boxed() operation
|
| 37 |
+
before converting to a list:
|
| 38 |
+
|
| 39 |
+
ArrayList<Integer> negatives = numbers.stream().mapToInt(number -> number).
|
| 40 |
+
filter(number -> number < 0).boxed().
|
| 41 |
+
collect(Collectors.toCollection(ArrayList::new));
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
Let's look at another example where we want to create a new list
|
| 49 |
+
that only includes those 'Student' objects with less than 30 credits:
|
| 50 |
+
|
| 51 |
+
ArrayList<Student> lessThan30 = students.stream().
|
| 52 |
+
filter(student -> student.getCredits() < 30).
|
| 53 |
+
collect(Collectors.toCollection(ArrayList::new));
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
|