Stream API Abw
Stream API Abw
1. configuration:
we can configure either by using filter mechanism or by using map mechanism.
Filtering:
we can configure a filter to filter elements from the collection based on some
boolean condition by using filter()method of Stream interface.
public Stream filter(Predicate<T> t)
here (Predicate<T > t ) can be a Boolean valued function/lambda expression
Ex:
Stream s=c.stream();
Stream s1=s.filter(i -> i%2==0);
Hence to filter elements of collection based on some boolean condition we
should go for filter()method.
Mapping:
If we want to create a separate new object, for every object present in the
collection based on our requirement then we should go for map () method of
Stream interface.
public Stream map (Function f); It can be lambda expression also
Ex:
Stream s = c.stream();
2. Processing
A) processing by collect() method
B) Processing by count()method
C) Processing by sorted()method
D) Processing by min() and max() methods
E) forEach() method
F) toArray() method
G) Stream.of()method
import java.util.*;
import java.util.stream.*;
class Test {
l1.add(i);
}
System.out.println(l1);
System.out.println(l2);
import java.util.stream.*;
class Test {
System.out.println(l);
System.out.println(l2);
The Stream.collect() Method
AD
3. Collectors
3.1. Collectors.toList()
AD
.collect(toList());
3.1.1. Collectors.toUnmodifiableList()
.collect(toUnmodifiableList());
.isInstanceOf(UnsupportedOperationException.class);
3.2. Collectors.toSet()
.collect(toSet());
AD
assertThat(result).hasSize(4);
3.2.1. Collectors.toUnmodifiableSet()
.collect(toUnmodifiableSet());
.isInstanceOf(UnsupportedOperationException.class);
3.3. Collectors.toCollection()
.collect(toCollection(LinkedList::new))
Notice that this will not work with any immutable collections. In such a case, we
would need to either write a custom Collector implementation or
use collectingAndThen.
3.4. Collectors.toMap()
keyMapper
valueMapper
Let's collect those elements into a Map that stores strings as keys and their
lengths as values:
AD
.collect(toMap(Function.identity(), String::length))
assertThatThrownBy(() -> {
listWithDuplicates.stream().collect(toMap(Function.identity(), String::length));
}).isInstanceOf(IllegalStateException.class);
Note that toMap doesn't even evaluate whether the values are also equal. If it
sees duplicate keys, it immediately throws an IllegalStateException.
The third argument here is a BinaryOperator, where we can specify how we want
collisions to be handled. In this case, we'll just pick any of these two colliding
values because we know that the same strings will always have the same lengths
too.
3.4.1. Collectors.toUnmodifiableMap()
.collect(toMap(Function.identity(), String::length))
As we can see, if we try to put a new entry into a result Map, we'll get
an UnsupportedOperationException:
.isInstanceOf(UnsupportedOperationException.class);
3.5. Collectors.collectingAndThen()
AD
.collect(collectingAndThen(toList(), ImmutableList::copyOf))
3.6. Collectors.joining()
.collect(joining());
"abbcccdd"
.collect(joining(" "));
This will result in:
AD
3.7. Collectors.counting()
.collect(counting());
3.8. Collectors.summarizingDouble/Long/Int()
.collect(summarizingDouble(String::length));
assertThat(result.getAverage()).isEqualTo(2);
assertThat(result.getCount()).isEqualTo(4);
assertThat(result.getMax()).isEqualTo(3);
assertThat(result.getMin()).isEqualTo(1);
assertThat(result.getSum()).isEqualTo(8);
3.9. Collectors.averagingDouble/Long/Int()
AveragingDouble/Long/Int is a collector that simply returns an average of
extracted elements.
.collect(averagingDouble(String::length));
3.10. Collectors.summingDouble/Long/Int()
AD
.collect(summingDouble(String::length));
3.11. Collectors.maxBy()/minBy()
.collect(maxBy(Comparator.naturalOrder()));
We can see that the returned value is wrapped in an Optional instance. This forces
users to rethink the empty collection corner case.
3.12. Collectors.groupingBy()
We can group them by string length, and store the grouping results
in Set instances:
.collect(groupingBy(String::length, toSet()));
This will result in the following being true:
assertThat(result)
.containsEntry(1, newHashSet("a"))
.containsEntry(3, newHashSet("ccc"));
AD
3.13. Collectors.partitioningBy()
We can write:
3.14. Collectors.teeing()
Let's find the maximum and minimum numbers from a given Stream using the
collectors we've learned so far:
Here we're using two different collectors, and then combining the results of those
two to create something meaningful. Before Java 12, in order to cover such use
cases, we had to operate on the given Stream twice, store the intermediate results
into temporary variables, and then combine those results afterwards.
Fortunately, Java 12 offers a built-in collector that takes care of these steps on
our behalf; all we have to do is provide the two collectors and the combiner
function.
Since this new collector tees the given stream towards two different directions,
it's called teeing:
numbers.stream().collect(teeing(
(min, max) -> // Receives the result from those collectors and combines them
));
B) Processing by count()method
this method returns number of elements present in the stream.
public long count()
Ex:
long count=l.stream().filter(s ->s.length()==5).count();
C) Processing by sorted()method
if we sort the elements present inside stream then we should go for sorted()
method.
the sorting can either default natural sorting order or customized sorting
order specified by comparator.
sorted()- default natural sorting order
sorted(Comparator c)-customized sorting order.
Ex:
List<String> l3=l.stream().sorted().collect(Collectors.toList());
List<String> l4=l.stream().sorted((s1,s2)->s1.compareTo(s2)).collect(Collectors.toList());
E) forEach() method
this method will not return anything.
this method will take lambda expression as argument and apply that lambda
expression for each element present in the stream.
Ex:
l.stream().forEach(s->sop(s));
l3.stream().forEach(System.out:: println);
Ex:
import java.util.*;
import java.util.stream.*;
class Test1 {
System.out.println(l1);
System.out.println(l2);
List<Integer> l3=l1.stream().sorted().collect(Collectors.toList());
System.out.println(l3);
Comparator<Integer> comp=(i1,i2)->i1.compareTo(i2);
List<Integer> l4=l1.stream().sorted(comp).collect(Collectors.toList());
System.out.println(l4);
Integer min=l1.stream().min(comp).get();
System.out.println(min);
Integer max=l1.stream().max(comp).get();
System.out.println(max);
l3.stream().forEach(i->sop(i));
l3.stream().forEach(System.out:: println);
}
F) toArray() method
we can use toArray() method to copy elements present in the stream into
specified array
Integer[] ir = l1.stream().toArray(Integer[] :: new);
for(Integer i: ir) {
sop(i);
G) Stream.of()method
we can also apply a stream for group of values and for arrays.
Ex:
Stream s=Stream.of(99,999,9999,99999);
s.forEach(System.out:: println);
Double[] d={10.0,10.1,10.2,10.3};
Stream s1=Stream.of(d);
s1.forEach(System.out :: println);