January 02, 2020

#Java8 Streams Examples

class Employee {
private int id;
private String name;
private double salary;
private Date dateOfJoining;
private int age;
public Employee(int id, String name, double salary,
Date dateOfJoining, int age) {
super();
this.id=id;
this.name = name;
this.salary = salary;
this.dateOfJoining = dateOfJoining;
this.age=age;
}
//getter, setters, tostring
}
view raw Employee.java hosted with ❤ by GitHub




public static List<Employee> getEmployees() throws Exception {
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
Date dateOfJoining1 = dateformat.parse("17/07/1989");
Date dateOfJoining2 = dateformat.parse("15/10/2007");
Date dateOfJoining3 = dateformat.parse("01/10/2020");
Date dateOfJoining4 = dateformat.parse("11/11/2020");
List<Employee> employees=new ArrayList<>();
employees.add(new Employee(1, "Ronalda", 5000, dateOfJoining1, 28));
employees.add(new Employee(2, "Matilda", 7000, dateOfJoining2, 32));
employees.add(new Employee(3, "Roslie", 10000, dateOfJoining3, 50));
employees.add(new Employee(4, "Martha", 55000, dateOfJoining4, 60));
return employees;
}
public static void main(String[] args) throws Exception{
List<Employee> employees=getEmployees();
//count the number of employees
long count=employees.stream().count();
//Sort employees based on Date of Joining
employees.stream()
.sorted((e1, e2)->e1.getDateOfJoining()
.compareTo(e2.getDateOfJoining()))
.collect(Collectors.toList());
//Sort employees based on Date of Joining
//using method reference
employees.stream()
.sorted(Comparator.comparing(Employee::getDateOfJoining))
.collect(Collectors.toList());
//Filter employees with salary less than 8000
employees.stream()
.filter(e->e.getSalary()<8000)
.collect(Collectors.toList());
//find top 3 highest earning employees
employees.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
.limit(3)
.map(Employee::getName)
.forEach(System.out::println);
//Sort employees by age using method reference
employees.stream()
.sorted(Comparator.comparing(Employee::getAge))
.collect(Collectors.toList());
//Sort employees by age in reverse order using method reference
employees.stream()
.sorted(Comparator.comparing(Employee::getAge).reversed())
.collect(Collectors.toList());
//Covert the list into map, where key:id, value:name
Map<Integer, String> empMap=employees.stream()
.collect(Collectors.toMap
(e->e.getId(), e->e.getName()));
//Covert the list into map using method ref, where key:id, value:name
empMap=employees.stream()
.collect(Collectors.toMap
(Employee::getId, Employee::getName));
//While converting to a map if the duplicate key is encountered
//it will throw 'java.lang.IllegalStateException: Duplicate key'.
//We can handle this by providing merging function.
empMap=employees.stream()
.collect(Collectors.toMap(e->e.getId(), e->e.getName(),
(oldName, newName)->oldName+newName));
//Print name of all the employees in captial letters in sorted order
employees.stream()
.map(e->e.getName())
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
//Find average age of employee
double averageAge=employees.stream()
.mapToInt(e->e.getAge())
.average().getAsDouble();
//OR
averageAge=employees.stream()
.collect(Collectors.averagingDouble(e -> e.getAge()));
//Print the max salary
employees.stream()
.mapToDouble(e->e.getSalary())
.max()
.ifPresent(System.out::println);
//groups all Employees by age
Map<Integer, List<Employee>> empAgeGroup=employees.stream()
.collect(Collectors.groupingBy(e -> e.getAge()));
//Convert employee names into a comma seperated string
String commaSepratedNames = employees.stream()
.map(Employee::getName)
.collect(Collectors.joining(", ", "{", "}"));
//Divide the employees into groups according to salary
//is greater than 5000
Map<Boolean, List<Employee>> mappedEmployees=employees.stream()
.collect(Collectors.partitioningBy
(e->e.getSalary()>5000));
//Increment the salary of each employee by 2000
employees.stream()
.peek(e -> e.setSalary(e.getSalary() + 2000))
.peek(System.out::println)
.collect(Collectors.toList());
//Find the youngest and oldest employee
Employee youngEmployee=employees.stream()
.min((e1, e2)->e1.getAge() - e2.getAge())
.orElseThrow(NoSuchElementException::new);
Employee oldEmployee=employees.stream()
.max(Comparator.comparing(Employee::getAge))
.orElseThrow(NoSuchElementException::new);
//Convert the list into Set of employee names
Set<String> empNames = employees.stream()
.map(Employee::getName)
.collect(Collectors.toSet());
//summaryStatistics()
//statics.getMin(), statics.getMax(), statics.getAverage()
//statics.getCount(), statics.getCount()
DoubleSummaryStatistics statics = employees.stream()
.mapToDouble(Employee::getSalary)
.summaryStatistics();
}


public static void main(String[] args) {
//Create empty Stream
Stream<String> streamEmpty = Stream.empty();
//Create Stream of Array
Stream<String> streamOfArray = Stream.of("a", "b", "c");
//Stream of Primitives
//range(int startInclusive, int endExclusive)
IntStream intStream = IntStream.range(1, 3);
//rangeClosed(int startInclusive, int endInclusive)
LongStream longStream = LongStream.rangeClosed(1, 3);
//Stream of dates with 1 day difference
Stream.iterate(LocalDate.now(),
date -> date.plusDays(1))
.limit(10)
.collect(Collectors.toList());
//Create a list of numbers starting from 1 till 10
List<Integer> intList = Stream.iterate(1, i -> i + 1)
.limit(10).collect(Collectors.toList());
//Reusing Stream
Supplier<Stream<String>> streamSupplier= () ->
Stream.of("d2", "a2", "b1", "b3", "a1")
.filter(s -> s.startsWith("a"));
streamSupplier.get().anyMatch(s -> true);
streamSupplier.get().noneMatch(s -> true);
/*
identity: the initial value for an accumulator or a default value
if a stream is empty and there is nothing to accumulate;
accumulator: a function which specifies a logic of aggregation
of elements. As accumulator creates a new value for every
step of reducing, the quantity of new values equals to the
stream's size and only the last value is useful.
combiner: a function which aggregates results of the accumulator.
Combiner is called only in a parallel mode to reduce results
of accumulators from different threads.
*/
OptionalInt reduced1 = IntStream.range(1, 4)
.reduce((a, b) -> a + b);
System.out.println(reduced1.getAsInt());// 6
//This will print 10+(1+2+3)
int reduced2 = IntStream.range(1, 4)
.reduce(10, (a, b) -> a + b);
System.out.println(reduced2);// 16
//This will also print 36
//10+1=11
//10+2=12
//10+3=13
//and combiner will add 11+12+13 and return 36
int reduced3 = Arrays.asList(1, 2, 3)
.parallelStream()
.reduce(10, // identity
(a, b) -> a + b, // accumulator
(x, y) -> {// combiner
return x + y;
});
System.out.println(reduced3);
int[] nums= {1,2,6,-1,6,8};
//get the minimum number from array
//this can throw error if min cannot be find
//e.g when the array is empty
int mininum=IntStream.of(nums)
.min().getAsInt();
//similarly we can use max(), average(),count(),sum()
//This will not throw error
IntStream.of(nums)
.min()
.ifPresent(min->System.out.println(min));
//get the first 3 distant numbers from nums array
IntStream.of(nums)
.distinct()
.sorted()//it will not mutate original array
.limit(3)
.forEach(System.out::println);
}


-K Himaanshu Shuklaa..

No comments:

Post a Comment