Stream API
Count
List<Integer> list = Arrays.asList(10, 5, 3, 9, 5, 4, 6);
long count = list.stream().count();
Reduce
long sum = list.stream().reduce(0, (a,b)->a+b);// Returns the sum
int sum = list.stream().reduce(0,Integer::sum);
long facto = list.stream().reduce(1, (a,b)->a*b);// Returns the factorial
long evenSum = list.stream().reduce(0, (t, u) ->(u % 2 == 0)?t + u: t);// Sum of even numbers
BinaryOperator<Integer> binOp = new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer previous, Integer current) {
if (current % 2 == 0) {
return previous + current;
}
return previous;
}
};
long count = list.stream().reduce(0, binOp);
System.out.println(count);
int min = list.stream().reduce(list.get(0),Integer::min);
int max = list.stream().reduce(list.get(0),Integer::max);
All Match
boolean x = list.stream().allMatch(n->n%0==1); // true if all are odd numbers
Any Match
boolean x = list.stream().anyMatch(n->n%0==1); // true if one is odd numbers
None Match
boolean x = list.stream().noneMatch(n->n<0);
Distinct
Stream<Integer> x = list.stream().distinct(); // Returns non duplicate stream
Drop While
List<Integer> list = Arrays.asList( 10, 8, 7, 5, 3, 6,10);
Collections.sort(list);
list = list.stream().dropWhile(n->n<8).collect(Collectors.toList());;
System.out.println(list);// [8, 10, 10]
Stream<String> listStream = Stream.of("hello", "educative", "hi", "edpresso");
List<String> strList = listStream.dropWhile(s -> s.length() >= 5).collect(Collectors.toList());
System.out.println(strList);// [hi, edpresso]
Sorted
List<Integer> list = Arrays.asList(10, 8, 7, 5, 3, 6, 10);
list.stream().sorted().forEach(System.out::println);
Flat Map
When we have stream of stream data we can use flat map to map to a stream
List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 8, 7, 5, 3, 6, 10),Arrays.asList(10, 8, 7, 5, 3, 6, 10),Arrays.asList(10, 8, 7, 5, 3, 6, 10));
List<Integer> list1 = list.stream().flatMap(n->n.stream()).collect(Collectors.toList());
System.out.println(list1);
Limit
List<Integer> list = Arrays.asList(10, 8, 7, 5, 3, 6, 10);
List<Integer> y = list.stream().sorted().limit(5).collect(Collectors.toList());
System.out.println(y);//[3, 5, 6, 7, 8]
Skip
List<Integer> list = Arrays.asList(10, 8, 7, 5, 3, 6, 10);
List<Integer> y = list.stream().skip(3).collect(Collectors.toList());
System.out.println(y);
Take While
list.stream().sorted().takeWhile(n -> n < 8).collect(Collectors.toList());
Sorting Using Comparator
import java.util.Arrays;import java.util.Comparator;import java.util.List;
public class Application { public static void main(String[] args) {
List<Student> list = Arrays.asList(new Student(10, "Dayalan"), new Student(9, "Sajini"), new Student(11, "Iniyal")); //Method 1 list.stream().sorted((o1, o2) -> (o1.age> o2.age)?1:-1).forEach(System.out::println); //Method 2 list.stream().sorted((o1, o2) -> Integer.compare(o1.age, o2.age)).forEach(System.out::println); //Method 3 list.stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println); //Method 4 list.sort(Comparator.comparing(Student::getAge)); System.out.println(list); }}
class Student {
int age; String name;
public Student(int age, String name) { this.age = age; this.name = name; }
@Override public String toString() { return "{\"age\":\"" + age + "\", \"name\":\"" + name + "\"}"; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
Multiple Fields for Sorting
class Address implements Comparable<Address> { private Long no; private String street; private String city;
public Long getNo() { return no; }
public void setNo(Long no) { this.no = no; }
public String getStreet() { return street; }
public void setStreet(String street) { this.street = street; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
@Override public int compareTo(Address o) { Comparator<Address> streetComp = (o1, o2) -> o1.getStreet().compareTo(o2.getStreet()); Comparator<Address> cityComp = (o1, o2) -> o1.getStreet().compareTo(o2.getStreet()); return Comparator.comparingLong(Address::getNo).thenComparing(streetComp).thenComparing(cityComp).compare(this, o); }
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Application {
public static void main(String[] args) {
List<Student> list = Arrays.asList(new Student(10, "Dayalan"), new Student(9, "Sajini"),
new Student(11, "Iniyal"));
//Method 1
list.stream().sorted((o1, o2) -> (o1.age> o2.age)?1:-1).forEach(System.out::println);
//Method 2
list.stream().sorted((o1, o2) -> Integer.compare(o1.age, o2.age)).forEach(System.out::println);
//Method 3
list.stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println);
//Method 4
list.sort(Comparator.comparing(Student::getAge));
System.out.println(list);
}
}
class Student {
int age;
String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "{\"age\":\"" + age + "\", \"name\":\"" + name + "\"}";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Multiple Fields for Sorting
class Address implements Comparable<Address> {
private Long no;
private String street;
private String city;
public Long getNo() {
return no;
}
public void setNo(Long no) {
this.no = no;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public int compareTo(Address o) {
Comparator<Address> streetComp = (o1, o2) -> o1.getStreet().compareTo(o2.getStreet());
Comparator<Address> cityComp = (o1, o2) -> o1.getStreet().compareTo(o2.getStreet());
return Comparator.comparingLong(Address::getNo).thenComparing(streetComp).thenComparing(cityComp).compare(this,
o);
}
}
Stream.Collections Class
List<String> list = Arrays.asList("2", "3", "5", "6", "10", "10", "11", "20", "52");
toList()
List<String> numMorethan8 = list.stream().filter(n->Integer.valueOf(n)>8).collect(Collectors.toList());
System.out.println(numMorethan8);
// Collected as a List, Output : [10, 10, 11, 20, 52]
toSet()
Set<String> numMorethanSet = list.stream().filter(n->Integer.valueOf(n)>8).collect(Collectors.toSet());
System.out.println(numMorethanSet);
// Collected as a non duplicate List out put : [11, 52, 20, 10]
joining()
String x = list.stream().filter(n->Integer.valueOf(n)>8).collect(Collectors.joining());
System.out.println(x);
// Collected as a List Output : 1010112052
List<Integer> numList = Arrays.asList(2,3,5,6,10,10,11,20,52);
String str= numList.stream().map(n->n.toString()).collect(Collectors.joining(","));
System.out.println(str);
// Collected as a List Output : 2,3,5,6,10,10,11,20,52
groupingBy()
List<Integer> numList = Arrays.asList(2, 3, 5, 6, 10, 10, 11, 20, 52);
Map<Object, List<Integer>> str = numList.stream()
.collect(Collectors.groupingBy(n -> n % 2 == 0 ? "Even" : "Odd"));
System.out.println(str);
// Collected as a List Output : {"Even":[2, 6, 10, 10, 20, 52], "Odd":[3, 5, 11]}
List<Student> listStudent = new ArrayList<Student>();
listStudent.add(new Student(10, "Dayalan"));
listStudent.add(new Student(10, "Sajini"));
listStudent.add(new Student(20, "Iniyal"));
listStudent.add(new Student(20, "Thambi"));
listStudent.add(new Student(25, "Anna"));
listStudent.add(new Student(25, "Thiya"));
Map<Integer, List<Student>> studentMapByAge = listStudent.stream().collect(Collectors.groupingBy(Student::getAge));
System.out.println(studentMapByAge);
//{20:[{"age":"20", "name":"Iniyal"}, {"age":"20", "name":"Thambi"}], 25:[{"age":"25", "name":"Anna"}, {"age":"25", "name":"Thiya"}], 10:[{"age":"10", "name":"Dayalan"}, {"age":"10", "name":"Sajini"}]}
averagingInt()
Double averageAge = listStudent.stream().collect(Collectors.averagingInt(Student::getAge));
System.out.println(averageAge);
partitionBy()
Map<Boolean, List<Student>> x = listStudent.stream().collect(Collectors.partitioningBy(n->n.getAge()>18));
System.out.println(x);
/*
* {false:[{"age":"10", "name":"Dayalan"}, {"age":"10", "name":"Sajini"}],
* true:[{"age":"20", "name":"Iniyal"}, {"age":"20", "name":"Thambi"},
* {"age":"25", "name":"Anna"}, {"age":"25", "name":"Thiya"}]}
*/
counting()
Long x = listStudent.stream().collect(Collectors.counting());
System.out.println(x);
maxBy()
Optional<Student> x = listStudent.stream().collect(Collectors.maxBy(Comparator.comparing(Student::getAge)));
System.out.println(x); // {"age":"25", "name":"Anna"}
toMap()
Map<String, Integer> x = listStudent.stream().collect(Collectors.toMap(Student::getName,Student::getAge ));
System.out.println(x); // {Dayalan=10, Iniyal=20, Sajini=10, Thambi=20, Thiya=25, Anna=25}
Comments
Post a Comment