In one of the previous post, listed all the java 8 stream coding questions and answers(blog post). Today's post we will discuss one of the important coding questions i.e to sort the list in ascending and descending order using java 8 stream api.
1) Sort the string of list object in ascending order using java 8 stream
import java.util.Arrays; import java.util.List; public class SortExample { public static void main(String[] args) { List<String> listOfStrings = Arrays.asList("A", "E", "B", "C"); listOfStrings.stream().sorted().forEach(s -> System.out.println(s)); } }
Output:- A
B
C
E
2) Sort the string of list object in descending order using java 8 stream
import java.util.Arrays; import java.util.Comparator; import java.util.List; public class SortExample { public static void main(String[] args) { List<String> listOfStrings = Arrays.asList("A", "E", "B", "C"); listOfStrings.stream().sorted(Comparator.reverseOrder())
.forEach(s -> System.out.println(s)); } }
Output:- E
C
B
A
3) Sort the custom(Employee class) java object of list in ascending or descending order using java 8 stream
Employee.java,
public class Employee { private Long id; private String firstName; private String lastName; private String address; //constructor, setter and getter // and toString metghod }
SortExample.java,
package com.main; import java.util.ArrayList; import java.util.List; public class SortExample { public static void main(String[] args) { Employee e1 = new Employee(1L, "Anil", "Nivargi", "XYZ"); Employee e2 = new Employee(2L, "Mahesh", "Nivargi", "XYZ"); List<Employee> employeeList = new ArrayList<>(); employeeList.add(e1); employeeList.add(e2); System.out.println("Sort a list in ascending order using firstName -"); //sort a list in ascending order using firstName employeeList.stream().sorted((s1,s2) ->
s1.getFirstName().compareTo(s2.getFirstName())).forEach(
s -> System.out.println(s));
System.out.println("Sort a list in descending order using firstName -"); //sort a list in descending order using firstName employeeList.stream().sorted((s1,s2) ->
s2.getFirstName().compareTo(s1.getFirstName())).forEach(
s -> System.out.println(s)); } }
Output:-
Sort a list in ascending order using firstName - Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ] Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ] Sort a list in descending order using firstName - Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ] Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]
Thank you reading the blog post.
Reference Posts:-
No comments:
Post a Comment