Java 8 Comparator

In this tutorial we will see some examples of how to use Java 8 Comparator both using Lambda Expression and in Streams.

Java 8 Comparator

Java 8 Comparator

Java Comparator Prior to Java 8

package lambda;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Java7Comparator {
	public static void main(String[] args) {
		List<Person> personList = Arrays.asList(new Person("Sridharan", "Nithyanandam", 30, 12345.8),
				new Person("Ram", "Kumar", 32, 432424.8), new Person("Vijay", "Devarkonda", 23, 34345323.8),
				new Person("Atal", "Bihari", 45, 34534.8));

		System.out.println("Before Sorting");
		personList.stream().forEach(System.out::println);

		// Sort by Age Ascending Order
		Collections.sort(personList, new Comparator<Person>() {
			@Override
			public int compare(Person arg0, Person arg1) {
				return arg0.getAge() - arg1.getAge();
			}
		});

		System.out.println("After Sorting By Age - Ascending Order");
		personList.stream().forEach(System.out::println);

		// Sort by Age Descending Order
		Collections.sort(personList, new Comparator<Person>() {
			@Override
			public int compare(Person arg0, Person arg1) {
				return arg1.getAge() - arg0.getAge();
			}
		});

		System.out.println("After Sorting By Age - Descending Order");
		personList.stream().forEach(System.out::println);

		// Sort by Last Name Ascending Order
		Collections.sort(personList, new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				return o1.getLastName().compareTo(o2.getLastName());
			}
		});

		System.out.println("After Sorting By LastName - Ascending Order");
		personList.stream().forEach(System.out::println);

		// Sort by Last Name Descending Order
		Collections.sort(personList, new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				return o2.getLastName().compareTo(o1.getLastName());
			}
		});

		System.out.println("After Sorting By LastName - Descending Order");
		personList.stream().forEach(System.out::println);

	}

}

Output

Before Sorting
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

After Sorting By Age
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

After Sorting By Age - Descsending
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

After Sorting By LastName - Ascending
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

Java 8 Comparator –  Without Using Collections.sort

From Java 8, directly we can use sort() method from List interface. Prior to Java 8, we should use Collections class.


personList.sort(new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				return o1.getAge() - o2.getAge();
			}
		});

Java 8 Comparator –  Using Lambda Expression


	personList.sort((p1, p2) -> p1.getAge() - p2.getAge());

Complete Example

package lambda;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class LambdaComparator {

	public static void main(String[] args) {
		List<Person> personList = Arrays.asList(new Person("Sridharan", "Nithyanandam", 30, 12345.8),
				new Person("Ram", "Kumar", 32, 432424.8), new Person("Vijay", "Devarkonda", 23, 34345323.8),
				new Person("Atal", "Bihari", 45, 34534.8));

		System.out.println("Before Sorting");
		personList.stream().forEach(System.out::println);

		// Sort by Age Ascending Order
		personList.sort(new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				return o1.getAge() - o2.getAge();
			}
		});

		System.out.println("After Sorting By Age - Ascending Order");
		personList.stream().forEach(System.out::println);

		// Sort by Age Descending Order
		personList.sort(new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				return o2.getAge() - o1.getAge();
			}
		});

		System.out.println("After Sorting By Age - Descending Order");
		personList.stream().forEach(System.out::println);

		// Sort by Age Ascending Order - Using Lambda Expression
		personList.sort((p1, p2) -> p1.getAge() - p2.getAge());
		System.out.println("After Sorting By Age - Ascending Order - Using Lambda Expression");
		personList.stream().forEach(System.out::println);
		// Sort by Age Descending Order - Using Lambda Expression
		Comparator<Person> personSorterDesc = (p1, p2) -> p2.getAge() - p1.getAge();
		personList.sort(personSorterDesc);
		System.out.println("After Sorting By Age - Descending Order - Using Lambda Expression");
		personList.stream().forEach(System.out::println);

		// Sort by Age Descending Order - Using Lambda Expression and reversed Method
		Comparator<Person> personSorterDescReversed = (p1, p2) -> p1.getAge() - p2.getAge();
		personList.sort(personSorterDescReversed.reversed());
		System.out.println("After Sorting By Age - Descending Order - Using Lambda Expression and reversed");
		personList.stream().forEach(System.out::println);

		// Sort by LastName Ascending Order - Using Lambda Expression
		Comparator<Person> personSortByLastName = (p1, p2) -> p1.getLastName().compareTo(p2.getLastName());
		personList.sort(personSortByLastName);
		System.out.println("After Sorting By LastName - Ascending Order - Using Lambda Expression");
		personList.stream().forEach(System.out::println);

		// Sort by LastName Descending Order - Using Lambda Expression and Reversed
		Comparator<Person> personSortByLastNameReversed = (p1, p2) -> p1.getLastName().compareTo(p2.getLastName());
		personList.sort(personSortByLastNameReversed.reversed());
		System.out.println("After Sorting By LastName - Ascending Order - Using Lambda Expression and Reversed");
		personList.stream().forEach(System.out::println);
	}

}

Output


Before Sorting

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

 

After Sorting By Age - Ascending Order

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

 

After Sorting By Age - Descending Order

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

 

After Sorting By Age - Ascending Order - Using Lambda Expression

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

 

After Sorting By Age - Descending Order - Using Lambda Expression

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

 

After Sorting By Age - Descending Order - Using Lambda Expression and reversed

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

 

After Sorting By LastName - Ascending Order - Using Lambda Expression

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

 

After Sorting By LastName - Ascending Order - Using Lambda Expression and Reversed

Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]

Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]

Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

Java 8 Comparator –  Using Stream Expression

List<Person> ageSortedList = personList.stream().sorted((p1, p2) -> p1.getAge() - p2.getAge())
				.collect(Collectors.toList());

Complete Example

package stream;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import lambda.Person;

public class StreamComparator {

	public static void main(String[] args) {
		List<Person> personList = Arrays.asList(new Person("Sridharan", "Nithyanandam", 30, 12345.8),
				new Person("Ram", "Kumar", 32, 432424.8), new Person("Vijay", "Devarkonda", 23, 34345323.8),
				new Person("Atal", "Bihari", 45, 34534.8));

		System.out.println("Before Sorting");
		personList.stream().forEach(System.out::println);

		List<Person> ageSortedList = personList.stream().sorted((p1, p2) -> p1.getAge() - p2.getAge())
				.collect(Collectors.toList());

		System.out.println("After Sorting By Age");
		ageSortedList.stream().forEach(System.out::println);

		List<Person> ageSortedDescList = personList.stream().sorted((p1, p2) -> -p1.getAge() - p2.getAge())
				.collect(Collectors.toList());

		System.out.println("After Sorting By Age - Descsending");
		ageSortedDescList.stream().forEach(System.out::println);

		Comparator<Person> comparator = (p1, p2) -> p1.getLastName().compareTo(p2.getLastName());
		List<Person> lastNameSortAscList = personList.stream()
				.sorted(comparator.reversed()).collect(Collectors.toList());
		System.out.println("After Sorting By LastName - Ascending");
		lastNameSortAscList.stream().forEach(System.out::println);

	}

}

Before Sorting
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

After Sorting By Age
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

After Sorting By Age - Descsending
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]

After Sorting By LastName - Ascending
Person [firstName=Sridharan, lastName=Nithyanandam, age=30, salary=12345.8]
Person [firstName=Ram, lastName=Kumar, age=32, salary=432424.8]
Person [firstName=Vijay, lastName=Devarkonda, age=23, salary=3.43453238E7]
Person [firstName=Atal, lastName=Bihari, age=45, salary=34534.8]

If you have any questions in this Java 8 Comparator, please comment your queries below. If you like this tutorial please share it with your friends.

References

Comparator Interface

Java Stream Filter – Examples

Java stream filter method is mainly used to filter out the elements from collection object based on some condition(s). In this tutorial, we will see some examples of Java Stream Filter.

Java Stream Filter

Java Stream Filter

Filter() method accepts a functional interface i.e. java.util.function.Predicate Interface and returns Stream object. The java.util.function.Predicate Interface has an abstract method test(), that accepts generic Object and returns a boolean.

filter() method is an intermediate operation so we can apply any other stream methods.

Examples for Java Stream Filter

In the first example, we will pass each element from integer list to filter method and checks whether the corresponding element is event or not, if it is even it will be added into the new list(using collect()).
 
 

List<Integer> evenList = integerList.stream().filter(i -> i % 2 == 0).collect(Collectors.toList());

 
 
In the second example, we will pass each element of String list to filter method and checks whether the string contains the string “Java” and add it to the new List.
 
 

List<String> javaList = stringList.stream().filter(i -> i.contains("Java")).collect(Collectors.toList());

 
 
In the third examples, using filter method we will check whether Java7 is present or not, filter will validate whether the string is present or not, then using findAny() and isPresent() we will return it as boolean.
 
 

Predicate<String> java7 = i -> i.equalsIgnoreCase("Java7");
boolean isJava7 = stringList.stream().filter(java7).findAny().isPresent();

 
 
In the forth example, we get the Java7 value if it present inside the list. Again here to validate we used filter() method. If Java7 is present, findAny() method will return that value, else orElse(null) method will return null value.
 
 

String java7Value = stringList.stream().filter(i -> i.equalsIgnoreCase("Java7")).findAny().orElse(null);

 
 
In the fifth example, we have list of person objects, and we filter it out by their salary greater than 100. As a result we will get new list which contains all the person whose salary is greater than 100.
 
 

List<Person> salaryGreaterThanHundred = personList.stream().filter(person -> person.getSalary() > 100)
				.collect(Collectors.toList());

 
 
 

In the last example, we try to get the person object whose name is “Sridhar”, here again using findAny we will get the corresponding Person object else using orElse() method we will get null.
 
 

Person Sridhar = personList.stream().filter(person -> person.getfName().equalsIgnoreCase("Sridhar")).findAny()
				.orElse(null);

 
 
 

Person.java

package com.learnfromexamples.java8tutorial.streams;
package com.learnfromexamples.java8tutorial.streams;
public class Person { 
       private String fName; 
       private String lName; 
       private double salary;
       // getters  setters, constructors, toString
}

 

StreamFilterExample.java

package com.learnfromexamples.java8tutorial.streams;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class StreamFilterExample {
	public static void main(String[] args) {

		List<Integer> integerList = Arrays.asList(12, 54, 67, 654, 56, 24, 76, 23, 79);
		/**
		 * Filter even numbers
		 */
		List<Integer> evenList = integerList.stream().filter(i -> i % 2 == 0).collect(Collectors.toList());

		evenList.stream().forEach(System.out::println);

		List<String> stringList = Arrays.asList("Spring", "Hibernate", "Java7", "Maven", "Java8");

		/**
		 * Filter String which contains Java
		 */
		List<String> javaList = stringList.stream().filter(i -> i.contains("Java")).collect(Collectors.toList());

		javaList.stream().forEach(System.out::println);

		/**
		 * Check if Java7 present inside list
		 */
		Predicate<String> java7 = i -> i.equalsIgnoreCase("Java7");
		boolean isJava7 = stringList.stream().filter(java7).findAny().isPresent();
		System.out.println(isJava7);

		/**
		 * Get Java7 if present inside list, else null
		 */
		String java7Value = stringList.stream().filter(i -> i.equalsIgnoreCase("Java7")).findAny().orElse(null);
		System.out.println(java7Value);

		List<Person> personList = Arrays.asList(new Person("Sridhar", "Nithyanandam", 123.13),
				new Person("Ram", "Kumar", 12433.13), new Person("Vijay", "Devarkonda", 32.13));

		personList.stream().forEach(System.out::println);

		/**
		 * Filter Persons whose salary is greater than 100
		 */
		List<Person> salaryGreaterThanHundred = personList.stream().filter(person -> person.getSalary() > 100)
				.collect(Collectors.toList());
		System.out.println("----");

		salaryGreaterThanHundred.stream().forEach(System.out::println);

		/**
		 * Get Sridhar Object if present inside list, else null
		 */
		Person Sridhar = personList.stream().filter(person -> person.getfName().equalsIgnoreCase("Sridhar")).findAny()
				.orElse(null);
		System.out.println("----");

		System.out.println(Sridhar);

	}
}

12
54
654
56
24
76
Java7
Java8
true
Java7
Person [fName=Sridhar, lName=Nithyanandam, salary=123.13]
Person [fName=Ram, lName=Kumar, salary=12433.13]
Person [fName=Vijay, lName=Devarkonda, salary=32.13]
----
Person [fName=Sridhar, lName=Nithyanandam, salary=123.13]
Person [fName=Ram, lName=Kumar, salary=12433.13]
----
Person [fName=Sridhar, lName=Nithyanandam, salary=123.13]


If you like this concept, please share it with your friends.

 

References:

Java Stream