AddThis

Thursday 5 September 2024

Solving real time queries using java 8 features stream api with examples

package com.pse;


import java.util.ArrayList;

import java.util.Arrays;

import java.util.Comparator;

import java.util.DoubleSummaryStatistics;

import java.util.List;

import java.util.Optional;

import java.util.stream.Collectors;


/**

 * @author shailesh

 */

public class Java8Test {

static List<Employee> employeeList = new ArrayList<Employee>();

static {

employeeList.add(new Employee(111, "Jiya Brein", 32, "Female", "HR", 2011, 25000.0));

employeeList.add(new Employee(122, "Paul Niksui", 25, "Male", "Sales And Marketing", 2015, 13500.0));

employeeList.add(new Employee(133, "Martin Theron", 29, "Male", "Infrastructure", 2012, 18000.0));

employeeList.add(new Employee(144, "Murali Gowda", 28, "Male", "Product Development", 2014, 32500.0));

employeeList.add(new Employee(155, "Nima Roy", 27, "Female", "HR", 2013, 22700.0));

employeeList.add(new Employee(166, "Iqbal Hussain", 43, "Male", "Security And Transport", 2016, 10500.0));

employeeList.add(new Employee(177, "Manu Sharma", 35, "Male", "Account And Finance", 2010, 27000.0));

employeeList.add(new Employee(188, "Wang Liu", 31, "Male", "Product Development", 2015, 34500.0));

employeeList.add(new Employee(199, "Amelia Zoe", 24, "Female", "Sales And Marketing", 2016, 11500.0));

employeeList.add(new Employee(200, "Jaden Dough", 38, "Male", "Security And Transport", 2015, 11000.5));

employeeList.add(new Employee(211, "Jasna Kaur", 27, "Female", "Infrastructure", 2014, 15700.0));

employeeList.add(new Employee(222, "Nitin Joshi", 25, "Male", "Product Development", 2016, 28200.0));

employeeList.add(new Employee(233, "Jyothi Reddy", 27, "Female", "Account And Finance", 2013, 21300.0));

employeeList.add(new Employee(244, "Nicolus Den", 24, "Male", "Sales And Marketing", 2017, 10700.5));

employeeList.add(new Employee(255, "Ali Baig", 23, "Male", "Infrastructure", 2018, 12700.0));

employeeList.add(new Employee(266, "Sanvi Pandey", 26, "Female", "Product Development", 2015, 28900.0));

employeeList.add(new Employee(277, "Anuj Chettiar", 31, "Male", "Product Development", 2012, 35700.0));

}

public static void main(String[] args) {

// Query 3.1 : How many male and female employees are there in the organization?

employeeList.stream().collect(Collectors.groupingBy(Employee::getGender, Collectors.counting())).entrySet()

.forEach(System.out::println);

System.out.println();


// Query 3.2 : Print the name of all departments in the organization?

employeeList.stream().map(Employee::getDepartment).distinct().forEach(System.out::println);

System.out.println();


// Query 3.3 : What is the average age of male and female employees?

employeeList.stream()

.collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingInt(Employee::getAge)))

.entrySet().forEach(System.out::println);

System.out.println();


// Query 3.4 : Get the details of highest paid employee in the organization?

Optional<Employee> employee = employeeList.stream()

.collect(Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary)));

System.out.println(employee);

// Or

Optional<Employee> employee2 = employeeList.stream().max(Comparator.comparingDouble(Employee::getSalary));

System.out.println(employee2);

System.out.println();


// Query 3.5 : Get the names of all employees who have joined after 2015?

employeeList.stream().filter(e -> e.getYearOfJoining() > 2015).map(Employee::getName)

.forEach(System.out::println);

System.out.println();


// Query 3.6 : Count the number of employees in each department?

employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting())).entrySet()

.forEach(System.out::println);

System.out.println();


// Query 3.7 : What is the average salary of each department?

employeeList.stream()

.collect(

Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)))

.entrySet().forEach(System.out::println);

System.out.println();


// Query 3.8 : Get the details of youngest male employee in the product

// development department?

Optional<Employee> youngestMaleEmployeeInProductDevelopmentWrapper = employeeList.stream()

.filter(e -> e.getGender().equals("Male") && e.getDepartment().equals("Product Development"))

.min(Comparator.comparingInt(Employee::getAge));

System.out.println(youngestMaleEmployeeInProductDevelopmentWrapper);

// Or

Optional<Employee> youngestMaleEmployeeInProductDevelopmentWrapper2 = employeeList.stream()

.filter(e -> e.getGender().equals("Male") && e.getDepartment().equals("Product Development"))

.collect(Collectors.minBy(Comparator.comparingInt(Employee::getAge)));

System.out.println(youngestMaleEmployeeInProductDevelopmentWrapper2);

System.out.println();


// Query 3.9 : Who has the most working experience in the organization?

Optional<Employee> mostWorkingExperienceEmployee = employeeList.stream()

.min(Comparator.comparingInt(Employee::getYearOfJoining));

System.out.println(mostWorkingExperienceEmployee);

// OR

Optional<Employee> mostWorkingExperienceEmployee2 = employeeList.stream()

.sorted(Comparator.comparingInt(Employee::getYearOfJoining)).findFirst();

System.out.println(mostWorkingExperienceEmployee2);

System.out.println();


// Query 3.10 : How many male and female employees are there in the sales and

// marketing team?

employeeList.stream().filter(e -> e.getDepartment().equals("Sales And Marketing"))

.collect(Collectors.groupingBy(Employee::getGender, Collectors.counting())).entrySet()

.forEach(System.out::println);

System.out.println();


// Query 3.11 : What is the average salary of male and female employees?

employeeList.stream()

.collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingDouble(Employee::getSalary)))

.entrySet().forEach(System.out::println);

System.out.println();


// Query 3.12 : List down the names of all employees in each department?

employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment)).entrySet().forEach(e -> {

System.out.println(e.getKey());

for (Employee emp : e.getValue()) {

System.out.println(emp);

}

});

System.out.println();


// Query 3.13 : What is the average salary and total salary of the whole

// organization?

DoubleSummaryStatistics doubleSummaryStatics = employeeList.stream()

.collect(Collectors.summarizingDouble(Employee::getSalary));

System.out.println(doubleSummaryStatics.getAverage());

System.out.println(doubleSummaryStatics.getSum());

System.out.println();


// Query 3.14 : Separate the employees who are younger or equal to 25 years from

// those employees who are older than 25 years.

employeeList.stream().collect(Collectors.partitioningBy(e -> e.getAge() > 25)).entrySet()

.forEach(System.out::println);

System.out.println();


// Query 3.15 : Who is the oldest employee in the organization? What is his age

// and which department he belongs to?

employeeList.stream().max(Comparator.comparingInt(Employee::getAge)).ifPresent(System.out::println);

                //Query 3.16 : Sort employee in descending order based on salary employeeList.stream()         .sorted(Comparator.comparingLong(Employee::getSalary).reversed())         .collect(toList());


                //Query 3.17 : Find 10th highest salary employee employeeList.stream()         .sorted(Comparator.comparingLong(Employee::getSalary).reversed()) .skip(9) .limit(1)         .collect(toList());


//Find max number in the list of integers

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

Integer maxObj = numbers.stream().collect(Collectors.maxBy(Comparator.naturalOrder())).get();

System.out.println(maxObj);


//OR

Integer i = numbers.stream().sorted(Comparator.reverseOrder()).findFirst().get();

System.out.println(i);

//How do you find the frequency of element in an array

List<String> listOfStrings = Arrays.asList("Pen", "Eraser", "Note Book", "Pen", "Pencil", "Pen", "Note Book", "Pencil");

Map<String, Long> elementCountMap = listOfStrings.stream()

                                                       .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

//Or

IntStream.of( 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 )

   .boxed()

   .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) ).entrySet().forEach(System.out::println);

   

//Sum number in a list

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

Integer sum = integers.stream().mapToInt(Integer::intValue).sum();

//OR

integers.stream().collect(Collectors.summingInt(Integer::intValue));

//Or

integers.stream().reduce(0, Integer::sum);

//Find only duplicate numbers

List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});

numbers.stream().filter(i -> Collections.frequency(numbers, i) >1)

        .collect(Collectors.toSet()).forEach(System.out::println);

//OR

List<Integer> duplicates = IntStream.of( 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 )

   .boxed()

   .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) )

   .entrySet()

   .stream()

   .filter( p -> p.getValue() > 1 )

   .map( Map.Entry::getKey )

   .collect( Collectors.toList() );

System.out.println(duplicates);

//Find distinct numbers in an array

int[] distinctArr = Arrays.stream(new int[] { 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 }).distinct().toArray();

Arrays.stream(distinctArr).forEach(System.out::println);

//Find distinct numbers in a list

Arrays.asList(new Integer[] { 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 }).stream()

.distinct().forEach(System.out::println);


                //Sort a map based on value

                Map<String, Integer> wordCounts = new HashMap<>();

wordCounts.put("USA", 100);

wordCounts.put("jobs", 200);

wordCounts.put("software", 50);

wordCounts.put("technology", 70);

wordCounts.put("opportunity", 200);

Map<String, Integer> sortedByCount = wordCounts.entrySet()

                .stream()

                .sorted(Map.Entry.comparingByValue())

                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1,                                 LinkedHashMap::new));

}

}


class Employee {

int id;

String name;

int age;

String gender;

String department;

int yearOfJoining;

double salary;


public Employee(int id, String name, int age, String gender, String department, int yearOfJoining, double salary) {

this.id = id;

this.name = name;

this.age = age;

this.gender = gender;

this.department = department;

this.yearOfJoining = yearOfJoining;

this.salary = salary;

}

public int getId() {

return id;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public String getGender() {

return gender;

}

public String getDepartment() {

return department;

}

public int getYearOfJoining() {

return yearOfJoining;

}

public double getSalary() {

return salary;

}

@Override

public String toString() {

return "Id : " + id + ", Name : " + name + ", age : " + age + ", Gender : " + gender + ", Department : "

+ department + ", Year Of Joining : " + yearOfJoining + ", Salary : " + salary;

}

}

 

No comments:

Post a Comment

Solving real time queries using java 8 features stream api with examples

package com.pse; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.DoubleSummaryStatistics;...