August 23, 2021

Sort with given object multiple properties names, age using JAVA8

List can be sorted using Java 8 Lambda Expressions, moving right past syntactic sugar and into real and powerful functional semantics. The implementation of all of these examples and code snippets can be found over on gitHub: https://github.com/ramanujadasu/tutorials/tree/master/core-java-modules/core-java-lambdas

List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), 
      new Human("Jack", 12)
    );


Basic Sort Without Lambdas:

    Collections.sort(humans, new Comparator<Human>() {
        @Override
        public int compare(Human h1, Human h2) {
            return h1.getName().compareTo(h2.getName());
        }
    });


Basic Sort With Lambda Support:

    humans.sort(
      (Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));


Basic Sorting With No Type Definitions:

	humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));

Sort Using Reference to Static Method:

public static int compareByNameThenAge(Human lhs, Human rhs) {
    if (lhs.name.equals(rhs.name)) {
        return Integer.compare(lhs.age, rhs.age);
    } else {
        return lhs.name.compareTo(rhs.name);
    }
}

humans.sort(Human::compareByNameThenAge);

Sort Extracted Comparators:

Collections.sort(
      humans, Comparator.comparing(Human::getName));

Reverse Sort:

Comparator<Human> comparator
      = (h1, h2) -> h1.getName().compareTo(h2.getName());
    
    humans.sort(comparator.reversed());


Sort With Multiple Conditions:

List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 12), 
      new Human("Sarah", 10), 
      new Human("Zack", 12)
    );
    
    humans.sort((lhs, rhs) -> {
        if (lhs.getName().equals(rhs.getName())) {
            return Integer.compare(lhs.getAge(), rhs.getAge());
        } else {
            return lhs.getName().compareTo(rhs.getName());
        }
    });

Sort With Multiple Conditions -Composition:

humans.sort(
      Comparator.comparing(Human::getName).thenComparing(Human::getAge)
    );

Sorting a List With Stream.sorted():

List<String> letters = Lists.newArrayList("B", "A", "C");
	
List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
==
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    
	Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
	
    	List<Human> sortedHumans = 
	      humans.stream().sorted(nameComparator).collect(Collectors.toList());

Or
  	List<Human> sortedHumans = humans.stream()
      	.sorted(Comparator.comparing(Human::getName))
      	.collect(Collectors.toList());


Sorting a List in Reverse With Stream.sorted():

List<String> letters = Lists.newArrayList("B", "A", "C");

    List<String> reverseSortedLetters = letters.stream()
      .sorted(Comparator.reverseOrder())
      .collect(Collectors.toList());
==
 List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    
	Comparator<Human> reverseNameComparator = 
      	(h1, h2) -> h2.getName().compareTo(h1.getName());

    	List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator)
    	 .collect(Collectors.toList());

Or
	List<Human> reverseSortedHumans = humans.stream()
      	.sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder()))
     	 .collect(Collectors.toList());

Null Values:
  List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12));

    humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
==
List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12), null);

    humans.sort((h1, h2) -> {
        if (h1 == null) {
            return h2 == null ? 0 : 1;
        }
        else if (h2 == null) {
            return -1;
        }
        return h1.getName().compareTo(h2.getName());
    });

Or	
   humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName)));
Or
   humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName)));

Reference:
https://www.baeldung.com/java-8-sort-lambda

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts