Java 8 - Questions and Answers - Set 2

 package javatechies.org.stream;


import java.util.ArrayList;

import java.util.Comparator;

import java.util.DoubleSummaryStatistics;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Optional;

import java.util.Set;

import java.util.stream.Collectors;


public class EmployeeStreamDemo {

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

public static void main(String[] args) {

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));


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

method1();

System.out.println("\n");

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

method2();

System.out.println("\n");

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

method3();

System.out.println("\n");

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

method4();

System.out.println("\n");

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

method5();

System.out.println("\n");

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

method6();

System.out.println("\n");

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

method7();

System.out.println("\n");

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

// development department?

method8();

System.out.println("\n");

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

method9();

System.out.println("\n");

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

// marketing team?

method10();

System.out.println("\n");

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

method11();

System.out.println("\n");

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

method12();

System.out.println("\n");

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

// organization?

method13();

System.out.println("\n");

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

// those employees who are older than 25 years.

method14();

System.out.println("\n");

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

// and which department he belongs to?

method15();

}


public static void method1() {

System.out.println("Query 1 : How many male and female employees are there in the organization?");

Map<String, Long> noOfMaleAndFemaleEmployees = employeeList.stream()

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

System.out.println(noOfMaleAndFemaleEmployees);

}


public static void method2() {

System.out.println("Query 2 : Print the name of all departments in the organization?");

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

}


public static void method3() {

System.out.println("Query 3 : What is the average age of male and female employees?");

Map<String, Double> averageAgeOfMaleAndFemaleEmployee = employeeList.stream()

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

System.out.println(averageAgeOfMaleAndFemaleEmployee);

}


public static void method4() {

System.out.println("Query 4 : Get the details of highest paid employee in the organization?");

Optional<Employee> highestPaidEmployeeWrapper = employeeList.stream()

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

System.out.println(highestPaidEmployeeWrapper.get().getName());

}


public static void method5() {

System.out.println("Query 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);

}


public static void method6() {

System.out.println("Query 6 : Count the number of employees in each department?");

Map<String, Long> employeeCountByDepartment = employeeList.stream()

.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));

Set<Entry<String, Long>> entrySet = employeeCountByDepartment.entrySet();

for (Entry<String, Long> entry : entrySet) {

System.out.println(entry.getKey() + " : " + entry.getValue());

}

}


public static void method7() {

System.out.println("Query 7 : What is the average salary of each department?");

Map<String, Double> avgSalaryOfDepartments=

employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));         

Set<Entry<String, Double>> entrySet = avgSalaryOfDepartments.entrySet();     

for (Entry<String, Double> entry : entrySet) 

{

    System.out.println(entry.getKey()+" : "+entry.getValue());

}

}


public static void method8() {

System.out.println("Query 8 : Get the details of youngest male employee in the product development department?");

Optional<Employee> youngestMaleEmployeeInProductDevelopmentWrapper=

employeeList.stream()

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

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

         

                              Employee youngestMaleEmployeeInProductDevelopment = youngestMaleEmployeeInProductDevelopmentWrapper.get();

         

System.out.println("Details Of Youngest Male Employee In Product Development");

System.out.println("----------------------------------------------");

System.out.println("ID : "+youngestMaleEmployeeInProductDevelopment.getId());

System.out.println("Name : "+youngestMaleEmployeeInProductDevelopment.getName());

         

}


public static void method9() {

System.out.println("Query 9 : Who has the most working experience in the organization?");

Optional<Employee> seniorMostEmployeeWrapper=

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

Employee seniorMostEmployee = seniorMostEmployeeWrapper.get();

System.out.println("Senior Most Employee Details :");

System.out.println("----------------------------");

System.out.println("ID : "+seniorMostEmployee.getId());

System.out.println("Name : "+seniorMostEmployee.getName());

}


public static void method10() {

System.out.println("Query 10 : How many male and female employees are there in the sales and marketing team?");

Map<String, Long> countMaleFemaleEmployeesInSalesMarketing=
employeeList.stream()
            .filter(e -> e.getDepartment()=="Sales And Marketing")
            .collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));

System.out.println(countMaleFemaleEmployeesInSalesMarketing);

}


public static void method11() {

System.out.println("Query 11 : What is the average salary of male and female employees?");

Map<String, Double> avgSalaryOfMaleAndFemaleEmployees=

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

System.out.println(avgSalaryOfMaleAndFemaleEmployees);

}


public static void method12() {

System.out.println("Query 12 : List down the names of all employees in each department?");

Map<String, List<Employee>> employeeListByDepartment=

employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment));

Set<Entry<String, List<Employee>>> entrySet = employeeListByDepartment.entrySet();

         

for (Entry<String, List<Employee>> entry : entrySet) 
{
    System.out.println("--------------------------------------");
    System.out.println("Employees In "+entry.getKey() + " : ");
    System.out.println("--------------------------------------");
             
    List<Employee> list = entry.getValue();
             
    for (Employee e : list) 
    {
        System.out.println(e.getName());
    }
}

}


public static void method13() {

System.out.println("Query 13 : What is the average salary and total salary of the whole organization?");

DoubleSummaryStatistics employeeSalaryStatistics=
employeeList.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
         
System.out.println("Average Salary = "+employeeSalaryStatistics.getAverage());
System.out.println("Total Salary = "+employeeSalaryStatistics.getSum());

}


public static void method14() {

System.out.println(

"Query 14 : Separate the employees who are younger or equal to 25 years from those employees who are older than 25 years.");

Map<Boolean, List<Employee>> partitionEmployeesByAge=
employeeList.stream().collect(Collectors.partitioningBy(e -> e.getAge() > 25));
         
Set<Entry<Boolean, List<Employee>>> entrySet = partitionEmployeesByAge.entrySet();
         
for (Entry<Boolean, List<Employee>> entry : entrySet) 
{
    System.out.println("----------------------------");
             
    if (entry.getKey()) 
    {
        System.out.println("Employees older than 25 years :");
    }
    else
    {
        System.out.println("Employees younger than or equal to 25 years :");
    }
             
    System.out.println("----------------------------");
             
    List<Employee> list = entry.getValue();
             
    for (Employee e : list) 
    {
        System.out.println(e.getName());
    }
}

}


public static void method15() {

System.out.println(

"Query 15 : Who is the oldest employee in the organization? What is his age and which department he belongs to?");

Optional<Employee> oldestEmployeeWrapper = employeeList.stream().max(Comparator.comparingInt(Employee::getAge));
        
Employee oldestEmployee = oldestEmployeeWrapper.get();
         
System.out.println("Name : "+oldestEmployee.getName());
         
System.out.println("Age : "+oldestEmployee.getAge());
         
System.out.println("Department : "+oldestEmployee.getDepartment());

}

}


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;
}
}

---

public class WordCount {

public static void main(String[] args) {

    String sentence = "alex brian brian brian charles alex charles david eric david";

    List<String> wordsList = Arrays.stream(sentence.split(" ")).collect(Collectors.toList());

    Map<String, Long> ss = wordsList.stream().collect(Collectors.groupingBy(s -> s,Collectors.counting()));

    System.out.println(ss);

}

}

Output( tested ):

{alex=2, eric=1, charles=2, david=2, brian=3}

---


public class Java8CommonProgrammingQA {

    public static void main(String[] args) {

        List<Student> studentList = Stream.of(

                new Student(1, "Rohit", 30, "Male", "Mechanical Engineering", "Mumbai", 122, Arrays.asList("+912632632782", "+1673434729929")),

                new Student(2, "Pulkit", 56, "Male", "Computer Engineering", "Delhi", 67, Arrays.asList("+912632632762", "+1673434723929")),

                new Student(3, "Ankit", 25, "Female", "Mechanical Engineering", "Kerala", 164, Arrays.asList("+912632633882", "+1673434709929")),

                new Student(4, "Satish Ray", 30, "Male", "Mechanical Engineering", "Kerala", 26, Arrays.asList("+9126325832782", "+1671434729929")),

                new Student(5, "Roshan", 23, "Male", "Biotech Engineering", "Mumbai", 12, Arrays.asList("+012632632782")),

                new Student(6, "Chetan", 24, "Male", "Mechanical Engineering", "Karnataka", 90, Arrays.asList("+9126254632782", "+16736784729929")),

                new Student(7, "Arun", 26, "Male", "Electronics Engineering", "Karnataka", 324, Arrays.asList("+912632632782", "+1671234729929")),

                new Student(8, "Nam", 31, "Male", "Computer Engineering", "Karnataka", 433, Arrays.asList("+9126326355782", "+1673434729929")),

                new Student(9, "Sonu", 27, "Female", "Computer Engineering", "Karnataka", 7, Arrays.asList("+9126398932782", "+16563434729929", "+5673434729929")),

                new Student(10, "Shubham", 26, "Male", "Instrumentation Engineering", "Mumbai", 98, Arrays.asList("+912632646482", "+16734323229929")))

                .collect(Collectors.toList());


     // 1. Find the list of students whose rank is in between 50 and 100

        List<Student> students = studentList.stream().filter(student -> student.getRank() > 50 && student.getRank() < 100)

                .collect(Collectors.toList());

       // System.out.println(students);


        //2. Find the Students who stays in Karnataka and sort them by their names

        List<Student> studentsByCity = studentList.stream().filter(student -> student.getCity().equals("Karnataka"))

                .sorted(Comparator.comparing(Student::getFirstName,Comparator.reverseOrder())).collect(Collectors.toList());

       // System.out.println(studentsByCity);


        // 3. Find all departments names

        List<String> deptNames = studentList.stream()

                .map(Student::getDept)

                .distinct()

                .collect(Collectors.toList());

        Set<String> deptNamesInSet = studentList

                .stream().map(Student::getDept)

                .collect(Collectors.toSet());

        //System.out.println(deptNames);

        //System.out.println(deptNamesInSet);


        //4.  Find all the contact numbers

        List<String> contacts = studentList.stream()

                .flatMap(student -> student.getContacts().stream())

                .distinct()

                .collect(Collectors.toList());

        System.out.println(contacts);

        //one2one-> map

        //one2many-> flatmap


        //5.  Group The Student By Department Names

        Map<String, List<Student>> studentMap = studentList.stream()

                .collect(Collectors.groupingBy(Student::getDept));

       // System.out.println(studentMap);


        //6. Find the department who is having maximum number of students

        Map.Entry<String, Long> results = studentList.stream()

                .collect(Collectors.groupingBy(Student::getDept, Collectors.counting()))

                .entrySet().stream().max(Map.Entry.comparingByValue()).get();

        System.out.println(results);


        //7. Find the average age of male and female students

        Map<String, Double> avgStudents = studentList.stream()

                .collect(Collectors

                        .groupingBy(Student::getGender,

                                Collectors.averagingInt(Student::getAge)));

        //System.out.println(avgStudents);


        //8. Find the highest rank in each department

        Map<String, Optional<Student>> stdMap = studentList.stream()

                .collect(Collectors.groupingBy(Student::getDept,

                        Collectors.minBy(Comparator.comparing(Student::getRank))));

        // System.out.println(stdMap);


         //9 .Find the student who has second rank

        Student student = studentList.stream()

                .sorted(Comparator.comparing(Student::getRank))

                .skip(2)

                .findFirst().get();

        System.out.println(student);

    }

}

===============

Convert lowercase to uppercase in java8 for arraylist:

1)List<String> list = Arrays.asList("a", "b", "c");

// Uppercase the list

list = list.stream().map(String::toUpperCase).collect(Collectors.toList());

// Print list elements

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


2)List<String> list = Arrays.asList("a", "b", "c");

List<String> output = list.stream().map( i -> i.toUpperCase()).collect(Collectors.toList());

 ( List<String> output = list.parallelStream().map( i -> i.toUpperCase()).collect(Collectors.toList()); : for more faster by multithread executio )

---

public static void main(String[] args) {

    String s="sdf sdfsdfsd sdfsdfsd sdfsdfsd sdf sdf sdf ";

    String st[]=s.split(" ");

    System.out.println(st.length);

    Map<String, Integer> mp= new TreeMap<String, Integer>();

    for(int i=0;i<st.length;i++){

        Integer count=mp.get(st[i]);

        if(count == null){

            count=0;

        }           

        mp.put(st[i],++count);

    }

   System.out.println(mp.size());

   System.out.println(mp.get("sdfsdfsd"));

}

---

public class CountDuplicateCharsJava8 {

    public static void main(String[] args) {

        // given input string

        String input = "JavaJavaEE";


        // convert string into stream

        Map < Character, Long > result = input

            .chars().mapToObj(c -> (char) c)

            .collect(Collectors.groupingBy(c -> c, Collectors.counting()));


        result.forEach((k, v) -> {

            if (v > 1) {

                System.out.println(k + " : " + v);

            }

        });

    }

}

Output:

a : 4

E : 2

v : 2

J : 2

---

String to string array:

 // Input string to be convert to string array

        String str = "Geeks for Geeks";

         String strArray[] = str.split(" ");

---

String array to list:

public class StringArrayTest {

   public static void main(String[] args) {  

      String[] words = {"ace", "boom", "crew", "dog", "eon"};  

      List<String> wordList = Arrays.asList(words);  

      for (String e : wordList) {  

         System.out.println(e);  

      }  

   }  

}

---

public class WordCount {

public static void main(String[] args) {

    String sentence = "alex brian brian brian charles alex charles david eric david";

    List<String> wordsList = Arrays.stream(sentence.split(" ")).collect(Collectors.toList());

    Map<String, Long> ss = wordsList.stream().collect(Collectors.groupingBy(s -> s,Collectors.counting()));

    System.out.println(ss);

}

}

Output( tested ):

{alex=2, eric=1, charles=2, david=2, brian=3}

=====

public class JavaDuplicated1 {

    public static void main(String[] args) {

        // 3, 4, 9

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

        Set<Integer> result = findDuplicateBySetAdd(list);

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

    }

    public static <T> Set<T> findDuplicateBySetAdd(List<T> list) {

        Set<T> items = new HashSet<>();

        return list.stream()

                .filter(n -> !items.add(n)) // Set.add() returns false if the element was already in the set.

                .collect(Collectors.toSet());

    }

}


(OR)


public class JavaDuplicated3 {

    public static void main(String[] args) {

        // 3, 4, 9

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

        Set<Integer> result = findDuplicateByFrequency(list);

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

    }

    public static <T> Set<T> findDuplicateByFrequency(List<T> list) {

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

                .collect(Collectors.toSet());

    }

}

O/P:

3

4

9

====================

Immutable Class in Java:

Declare the class as final so it can’t be extended.

Make all of the fields private so that direct access is not allowed.

Don’t provide setter methods for variables.

Make all mutable fields final so that a field’s value can be assigned only once.

Initialize all fields using a constructor method performing deep copy.

Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.


final class ImmutableClass {

   private final int id;

   private final String name;

   public ImmutableClass(int id, String name) {

      this.id = id;

      this.name = name;

   }

   public int getId() {

      return id;

   }

   public String getName() {

      return name;

   }

}

class Main{

    public static void main(String args[]){

        ImmutableClass obj = new ImmutableClass(123, "PrepBuddy");

        System.out.println("The name of the object is "+ obj.getName());

    }

}

====================

compiled fine, tested:

@FunctionalInterface

public interface Interf1 {

void f();

}


@FunctionalInterface

interface Interf2 extends Interf1{

void f();

}


class Cls implements Interf1, Interf2 {

@Override

public void f() {

// TODO Auto-generated method stub

}

}

============

Error: Invalid '@FunctionalInterface' annotation; Interf2 is not a functional interface

@FunctionalInterface

public interface Interf1 {

void f1();

}

@FunctionalInterface

interface Interf2 extends Interf1{ // error:Invalid '@FunctionalInterface' annotation; Interf2 is not a functional interface

void f2();

}

===

public class Customer {
    private int id;
    private String name;
    private String email;
    private List<String> phoneNumbers;
    //setteres and getters and constructors
    }


public class EkartDataBase {
    public static List<Customer> getAll() {

        return Stream.of(
                new Customer(101, "john", "john@gmail.com", Arrays.asList("397937955", "21654725")),
                new Customer(102, "smith", "smith@gmail.com", Arrays.asList("89563865", "2487238947")),
                new Customer(103, "peter", "peter@gmail.com", Arrays.asList("38946328654", "3286487236")),
                new Customer(104, "kely", "kely@gmail.com", Arrays.asList("389246829364", "948609467"))
        ).collect(Collectors.toList());

    }
}


public class MapVsFlatMap {

    public static void main(String[] args) {

        List<Customer> customers = EkartDataBase.getAll();

        //List<Customer>  convert List<String> -> Data Transformation

        //mapping : customer -> customer.getEmail()

        //customer -> customer.getEmail()  *************** one to one mapping**********

        List<String> emails = customers.stream()

                .map(customer -> customer.getEmail())

                .collect(Collectors.toList());

        System.out.println(emails);


//customer -> customer.getPhoneNumbers()  ->> *************** one to many mapping****************

        //customer -> customer.getPhoneNumbers()  ->> one to many mapping

        List<List<String>> phoneNumbers = customers.

                stream().map(customer -> customer.getPhoneNumbers())

                .collect(Collectors.toList());

        System.out.println(phoneNumbers);


        //List<Customer>  convert List<String> -> Data Transformation

        //mapping : customer -> phone Numbers

        //customer -> customer.getPhoneNumbers()  ->> ************* one to many mapping**************

        List<String> phones = customers.stream()

                .flatMap(customer -> customer.getPhoneNumbers().stream())

                .collect(Collectors.toList());

        System.out.println(phones);

    }

}

===

public class SortEmployeeExample {

    public static void main(String[] args) {

        List<Employee> employees = new ArrayList<>();

        employees.add(new Employee("John", 50000));

        employees.add(new Employee("Jane", 60000));

        employees.add(new Employee("Jack", 40000));


        // Sort by name in ascending order

        List<Employee> sortedByNameAsc = employees.stream()

                .sorted(Comparator.comparing(Employee::getName))

                .collect(Collectors.toList());


        System.out.println("Sorted by Name (Ascending):");

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

    }

}

Sorted by Name (Ascending):

Employee{name='Jack', salary=40000.0}

Employee{name='Jane', salary=60000.0}

Employee{name='John', salary=50000.0}

--

public class SortEmployeeExample {

    public static void main(String[] args) {

        List<Employee> employees = new ArrayList<>();

        employees.add(new Employee("John", 50000));

        employees.add(new Employee("Jane", 60000));

        employees.add(new Employee("Jack", 40000));


        // Sort by name in descending order

        List<Employee> sortedByNameDesc = employees.stream()

                .sorted(Comparator.comparing(Employee::getName).reversed())

                .collect(Collectors.toList());


        System.out.println("Sorted by Name (Descending):");

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

    }

}

Sorted by Name (Descending):

Employee{name='John', salary=50000.0}

Employee{name='Jane', salary=60000.0}

Employee{name='Jack', salary=40000.0}

===

public class StreamListSorting {

    public static void main(String[] args) {


        // sort employee by salary in ascending order

        List < Employee > employees = new ArrayList < Employee > ();

        employees.add(new Employee(10, "Ramesh", 30, 400000));

        employees.add(new Employee(20, "John", 29, 350000));

        employees.add(new Employee(30, "Tom", 30, 450000));

        employees.add(new Employee(40, "Pramod", 29, 500000));


        List < Employee > employeesSortedList1 = employees.stream()

            .sorted((o1, o2) -> (int)(o1.getSalary() - o2.getSalary())).collect(Collectors.toList());

        System.out.println(employeesSortedList1);


        List < Employee > employeesSortedList2 = employees.stream()

            .sorted(Comparator.comparingLong(Employee::getSalary)).collect(Collectors.toList()); //ascending order

        System.out.println(employeesSortedList2);

    }

}

Output:

[Employee [id=20, name=John, age=29, salary=350000], Employee [id=10, name=Ramesh, age=30, salary=400000], Employee [id=30, name=Tom, age=30, salary=450000], Employee [id=40, name=Pramod, age=29, salary=500000]]

[Employee [id=20, name=John, age=29, salary=350000], Employee [id=10, name=Ramesh, age=30, salary=400000], Employee [id=30, name=Tom, age=30, salary=450000], Employee [id=40, name=Pramod, age=29, salary=500000]]

===

public class StreamListSorting {

    public static void main(String[] args) {

        // sort employee by salary in ascending order

        List < Employee > employees = new ArrayList < Employee > ();

        employees.add(new Employee(10, "Ramesh", 30, 400000));

        employees.add(new Employee(20, "John", 29, 350000));

        employees.add(new Employee(30, "Tom", 30, 450000));

        employees.add(new Employee(40, "Pramod", 29, 500000));


        List < Employee > employeesSortedList1 = employees.stream()

            .sorted((o1, o2) -> (int)(o2.getSalary() - o1.getSalary())).collect(Collectors.toList());

        System.out.println(employeesSortedList1);


        List < Employee > employeesSortedList2 = employees.stream() .sorted(Comparator.comparingLong(Employee::getSalary).reversed()).collect(Collectors.toList()); //ascending order

        System.out.println(employeesSortedList2);

    }

}

Output:

[Employee [id=40, name=Pramod, age=29, salary=500000], Employee [id=30, name=Tom, age=30, salary=450000], Employee [id=10, name=Ramesh, age=30, salary=400000], Employee [id=20, name=John, age=29, salary=350000]]

[Employee [id=40, name=Pramod, age=29, salary=500000], Employee [id=30, name=Tom, age=30, salary=450000], Employee [id=10, name=Ramesh, age=30, salary=400000], Employee [id=20, name=John, age=29, salary=350000]]

=====

public class StreamListSorting {

    public static void main(String[] args) {

        List < String > fruits = new ArrayList < String > ();

        fruits.add("Banana");

        fruits.add("Apple");

        fruits.add("Mango");

        fruits.add("Orange");


        List < String > sortedList = fruits.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());

        System.out.println(sortedList);


        List < String > sortedList1 = fruits.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());

        System.out.println(sortedList1);


        List < String > sortedList2 = fruits.stream().sorted().collect(Collectors.toList());

        System.out.println(sortedList2);

    }

}

Output:

[Apple, Banana, Mango, Orange]

[Apple, Banana, Mango, Orange]

[Apple, Banana, Mango, Orange]

====

public class StreamListSorting {

    public static void main(String[] args) {

        List < String > fruits = new ArrayList < String > ();

        fruits.add("Banana");

        fruits.add("Apple");

        fruits.add("Mango");

        fruits.add("Orange");


        // descending order

        List < String > sortedList3 = fruits.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

        System.out.println(sortedList3);


        List < String > sortedList4 = fruits.stream().sorted((o1, o2) -> o2.compareTo(o1)).collect(Collectors.toList());

        System.out.println(sortedList4);

    }

}

Output:

[Orange, Mango, Banana, Apple]

[Orange, Mango, Banana, Apple]

=====

Sort MAP values:

Map<Integer, String> sortedMap =      unsortedMap.entrySet().stream().sorted(Entry.comparingByValue())

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


Map<Integer, String> sortedMap =    unsortedMap.entrySet().stream()

                .sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue()))

                .forEach(k -> System.out.println(k.getKey() + ": " + k.getValue()));

===                

-- Sreenivas