•
•
•
•
224.
Collections actually store the data. A stream on the other
hand does not store any data, it just performs some
operations
on the underlying data
When you perform an operation on a Collection, the
Collection gets modified. When you perform an operation on a
Stream obtained on a Collection,
the underlying Collection
does not get modified
A Collection can be modified after it is created. A Stream on
the other hand cannot be modified after it is constructed
You can traverse a Collection any number of times. However,
you can traverse a Stream only once.
If you wish to traverse
over a Stream again it is not possible, you need to create a
new Stream from the underlying source and traverse it again
Suppose you have a List of String values. You want to
create a new List that eliminates the duplicates from the
original List and has the String values in uppercase. How
will you achieve this via Stream operations?
Answer:
The following code snippet demonstrates the above requirement:
List
fruits =
Arrays.asList(“Apple”,”Mango”,“Banana”,”Apple”,
”Orange”, “Mango”,”Strawberry”); //Line 1
List uniqueFruits =
fruits.stream().distinct().map(str–>
str.toUpperCase()).collect(Collectors.toList()); //Line
2
uniqueFruits.forEach(str–>
System.out.println(str));//Line 3
225.
This code first creates a List of String values called fruits at
Line 1. Line 2 first invokes the fruits.stream() which obtains
a Stream on the fruits List. It then invokes the distinct()
operation. The distinct() method returns a new Stream that
consists of only the distinct elements in the input Stream. Next, it
invokes the map() operation. The map() operation can be used
to transform a Stream. It accepts
as parameter a Function
instance and applies the Function to each element in the
Stream. Here, a lambda expression is used to convert each
String in the Stream to uppercase. Finally, it invokes the
collect() method, passing in a Collector that
converts the
Stream to a List. Line 3 then prints all the elements in the
uniqueFruits List. So, this code prints the following output:
APPLE
MANGO
BANANA
ORANGE
STRAWBERRY
Do'stlaringiz bilan baham: