Month: May 2016

Java 8 – Sorted Map By Key & Value

Posted on

Java-8

 

 

 

Below example will show, how to sort Collection & Map element by Key & Value using Lambda Expression in Java 8.

Example 1

In this example, we will see how to sort  element of Collection using Lambda expression.


        List listOfString = new ArrayList<>();
        listOfString.add("Z");
        listOfString.add("Q");
        listOfString.add("D");
        listOfString.add("A");
        listOfString.add("H");
        listOfString.add("T");

        listOfString.stream().sorted((e1,e2)->e1.compareTo(e2)).forEach(e->{
            System.out.println(" sorted list of String "+e);
        });
        // return new sorted list.
        /*        
        listOfString = listOfString.stream()
                                   .sorted((e1,e2)->e1.compareTo(e2))
                                   .collect(Collectors.toList());
        listOfString.forEach(e->{
            System.out.println(" sorted list of String "+e);
        });*/

Output:-
sorted list of String A
sorted list of String D
sorted list of String H
sorted list of String Q
sorted list of String T
sorted list of String Z

Example 2 : See how to sort a List’s Person by Name.

 


        List list = new ArrayList();

        list.add(new Person(6, "FF", 13, Person.SEX.MALE, "GOA"));
        list.add(new Person(7, "GG", 31, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(8, "HH", 30, Person.SEX.MALE, "Mumbai"));
        list.add(new Person(9, "II", 22, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(1, "AA", 12, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(2, "BB", 22, Person.SEX.FEMALE, "MP"));
        list.add(new Person(3, "CC", 44, Person.SEX.FEMALE,"UP"));
        list.add(new Person(4, "DD", 25, Person.SEX.MALE, "Gurgaon"));
        list.add(new Person(5, "EE", 51, Person.SEX.FEMALE, "GOA"));

         // sorted Person by name
        List sortedList = list.stream()
                .sorted((p1,p2)->p1.getName().compareTo(p2.getName()))
                .collect(Collectors.toList());
        sortedList.forEach(p->System.out.println("sorted by name :: "+p.toString()));


output :-
sorted by name :: Person{id=1, name=’AA’, age=12, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=2, name=’BB’, age=22, gender=FEMALE, location=’MP’}
sorted by name :: Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’UP’}
sorted by name :: Person{id=4, name=’DD’, age=25, gender=MALE, location=’Gurgaon’}
sorted by name :: Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’GOA’}
sorted by name :: Person{id=6, name=’FF’, age=13, gender=MALE, location=’GOA’}
sorted by name :: Person{id=7, name=’GG’, age=31, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=8, name=’HH’, age=30, gender=MALE, location=’Mumbai’}
sorted by name :: Person{id=9, name=’II’, age=22, gender=FEMALE, location=’Delhi’}

Example 3:- See how to sort a Map by value element


        //Sort a Map by their Value.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByValue())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [5=a, 9=c, 3=f, 6=k, 1=z]

Example 4:- See how to sort a Map by Key element


        //Sort a Map by their Key.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByKey())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [1=z, 3=f, 5=a, 6=k, 9=c]

Example 5:-

Here, A Map<String,Person> is created where String & Person object are taken as a Key & Value elements. First we will sort by Key elements then sort by Value elements in this below example.

Sorted by Map’s Key –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream()
                .sorted((e1,e2)->e1.getKey().compareTo(e2.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 

a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}

Final output give us a Map which values are sorted location field –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
                e1.getValue().getLocation().compareTo(e2.getValue().getLocation()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}

 

There are lots of ways to do this work depends on the requirement. Hope you enjoy this post.
Thanks
——–
Advertisements

Java 8 – Predicate Example

Posted on Updated on

Java-8

 

 

 

Predicate:-

Predicates represent single argument functions that return a boolean value. It can be applied to any Collection/group of similar Objects that is evaluated by a Predicate  condition.

A Predicate is a Functional Interface,we can pass lambda expressions wherever predicate is expected. Although Predicate is not only a Functional Interface in Java 8 but a set of standard  Functional Interfaces are given for developer in Java 8 as below :-

  • Predicate: A property of the object passed as argument
  • Consumer: An action to be performed with the object passed as argument
  • Function: Transform a T to a U
  • Supplier: Provide an instance of a T (such as a factory)
  • UnaryOperator: A unary operator from T -> T
  • BinaryOperator: A binary operator from (T, T) -> T

Below is simple defined Predicate  by inline lambda expression:-


Predicate checkFemale = (p)->p.getGender()==SEX.FEMALE;
Predicate checkMale = (p)->p.getGender()==SEX.MALE;
Predicate checkJuniorMalePerson = (p)->p.getGender()==SEX.MALE && p.getAge() <=18;
Predicate checkSeniorFemalePerson = (p)->p.getGender()==SEX.FEMALE && p.getAge() > 18;
Predicate checkNCRRegionPerson = (p) -> p.getLocation().equalsIgnoreCase("Delhi") 
					|| p.getLocation().equalsIgnoreCase("Noida")
					|| p.getLocation().equalsIgnoreCase("Gurgaon");

 

In the below example,  We have a list of Employee Object having some pre-defined properties and base on a condition or set of conditions, group of Objects get evaluated.



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

import com.example.model.Person.SEX;

public class PersonPredicateTest {

	public static void main(String args[]) {
		Person person1 = new Person(1, "AA", 12, SEX.FEMALE, "Delhi");
		Person person2 = new Person(2, "BB", 22, SEX.FEMALE, "MP");
		Person person3 = new Person(3, "CC", 44, SEX.MALE, "UP");
		Person person4 = new Person(4, "DD", 25, SEX.MALE, "Gurgaon");
		Person person5 = new Person(5, "EE", 51, SEX.FEMALE, "GOA");
		Person person6 = new Person(6, "FF", 13, SEX.MALE, "GOA");
		Person person7 = new Person(7, "GG", 31, SEX.FEMALE, "Delhi");
		Person person8 = new Person(8, "HH", 30, SEX.MALE, "Mumbai");
		Person person9 = new Person(9, "II", 22, SEX.FEMALE, "Delhi");

		List listOfEmployee = new ArrayList<>(Arrays.asList(
				new Person[] { person1, person2, person3, person4, person5, person6, person7, person8, person9 }));

		// Get All Junior Female
		System.out.println("############ Get All Female ##############");
		process(listOfEmployee, checkFemale()).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Female
		System.out.println("############ Get All Female ##############");
		process(listOfEmployee, checkMale()).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Person who is living in NCR Region
		System.out.println("############ Get All Junior Person who is living in NCR Region ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkNCRRegionPerson())).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Female
		System.out.println("############ Get All Junior Female ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkFemale())).forEach(p -> {
			System.out.println(p.toString());
		});
		// Get All Junior Male
		System.out.println("############ Get All Junior Male ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkMale())).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Delhi Regional Senior Person
		System.out.println("############ Get All Delhi Regional Senior Person ##############");
		Collection listOfDelhiRegionPerson = process(listOfEmployee,
				checkSeniorPerson().and(checkRegion("delhi")));
		listOfDelhiRegionPerson.forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Senior Female
		System.out.println("############ Get All Senior Female ##############");
		process(listOfEmployee, checkSeniorPerson().and(checkFemale())).forEach(p -> {
			System.out.println(p.toString());
		});
		// Get All Senior Male
		System.out.println("############ Get All Senior Male ##############");
		process(listOfEmployee, checkSeniorPerson().and(checkMale())).forEach(p -> {
			System.out.println(p.toString());
		});

	}

	private static Predicate checkJuniorPerson() {
		return (p) -> p.getAge() <= 18;
	}

	private static Predicate checkSeniorPerson() {
		return (p) -> p.getAge() > 18;
	}

	private static Predicate checkNCRRegionPerson() {
		return (p) -> p.getLocation().equalsIgnoreCase("Delhi") 
				|| p.getLocation().equalsIgnoreCase("Noida")
				|| p.getLocation().equalsIgnoreCase("Gurgaon");
	}

	private static Predicate checkMale() {
		return (p) -> p.getGender() == SEX.MALE;
	}

	private static Predicate checkRegion(String location) {
		return (p) -> p.getLocation().equalsIgnoreCase(location);
	}

	private static Predicate checkFemale() {
		return (p) -> p.getGender() == SEX.FEMALE;
	}

	public static  Collection process(Collection collection, Predicate predicate) {
		return collection.stream().filter(predicate).collect(Collectors. toList());
	}

}


Person.Java


public class Person {

	public enum SEX {
		MALE, FEMALE
	}

	private long id;
	private String name;
	private int age;
	private SEX gender;
	private String location;
        // Constructor here
        // Getter && Setter ....

Output :

############ Get All Female ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
Person [id=2, name=BB, age=22, gender=FEMALE, location=MP]
Person [id=5, name=EE, age=51, gender=FEMALE, location=GOA]
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Female ##############
Person [id=3, name=CC, age=44, gender=MALE, location=UP]
Person [id=4, name=DD, age=25, gender=MALE, location=Gurgaon]
Person [id=6, name=FF, age=13, gender=MALE, location=GOA]
Person [id=8, name=HH, age=30, gender=MALE, location=Mumbai]
############ Get All Junior Person who is living in NCR Region ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
############ Get All Junior Female ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
############ Get All Junior Male ##############
Person [id=6, name=FF, age=13, gender=MALE, location=GOA]
############ Get All Delhi Regional Senior Person ##############
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Senior Female ##############
Person [id=2, name=BB, age=22, gender=FEMALE, location=MP]
Person [id=5, name=EE, age=51, gender=FEMALE, location=GOA]
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Senior Male ##############
Person [id=3, name=CC, age=44, gender=MALE, location=UP]
Person [id=4, name=DD, age=25, gender=MALE, location=Gurgaon]
Person [id=8, name=HH, age=30, gender=MALE, location=Mumbai]