Lambda Expressions with Collections in Java 8

Lambda Expressions with Collections in Java 8

Articles & Tutorials Programming

 

The collection is nothing but a group of objects represented as a single entity. The important Collection types are:

  1. List
  2. Set
  3. Map

 

List:

If we want to represent a group of objects as a single entity where duplicate objects are allowed and insertion order is preserved then we should go for List.

  1. Insertion order is preserved
  2. Duplicate objects are allowed

 

The main implementation classes of List interface are:

  1. ArrayList
  2. LinkedList
  3. Vector
  4. Stack

 

Example:

import java.util.ArrayList; 

class Test{ 
   
  public static void main(String[] args){ 
   
    ArrayList<String> l = new ArrayList<String>(); 
    l.add("Fayçal"); 
    l.add("Karim"); 
    l.add("Amine"); 
    l.add("Azzedine"); 
    System.out.println(l); 
  } 
}

 

The result : [Fayçal, Karim, Amine, Azzedine]

 

Note: List (maybe ArrayList, LinkedList,Vector or Stack) never talks about sorting order. If we want sorting for the list then we should use Collections class sort() method.

Collecttions.sort(list)==>meant for Default Natural Sorting Order
Collections.sort(list,Comparator)==>meant for Customized Sorting Order

 

Set:

If we want to represent a group of individual objects as a single entity where duplicate objects are not allowed and insertion order is not preserved then we should go for Set.

  1. Insertion order is not preserved
  2. Duplicates are not allowed. If we are trying to add duplicates then we won’t get any error, just add() method returns false.

The following are important Set implementation classes: HashSet, TreeSet, etc

 

Example:

import java.util.HashSet;

class Test{
   public static void main(String[] args) {
   
     HashSet<String> l = new HashSet<String>();
     l.add("Fayçal"); 
     l.add("Amine");
     l.add("Amine");
     l.add("Azzedine");
     System.out.println(l);
 }
}

 

The result: [Fayçal, Amine, Azzedine]

Note: In the case of Set, if we want sorting order then we should go for: TreeSet

 

 

Map:

If we want to represent objects as key-value pairs then we should go for Map

for example :

id–>Name
mobilenumber–>address

The important implementation classes of Map are HashMap and TreeMap

 

Example:

import java.util.HashMap;

class Test {
  
   public static void main(String[] args){
	
	HashMap<String,String> m= new HashMap<String,String>();
	m.put("A","Apple");
	m.put("Z","Zebra");
	m.put("Fayçal","Java");
	m.put("B","Boy");
	m.put("T","Tiger");
	System.out.println(m);
  }
}

 

The result: {A=Apple, B=Boy, T=Tiger, Z=Zebra, Fayçal=Java}

Sorted Collections:

  1. Sorted List
  2. Sorted Set
  3. Sorted Map

 

1. Sorted List:

List (maybe ArrayList, LinkedList, Vector, or Stack) never talks about sorting order. If we want to sort for the list then we should use the Collections class sort() method.

Collections.sort(list) ==> meant for Default Natural Sorting Order
For String objects: Alphabetical Order
For Numbers: Ascending order

Instead of Default natural sorting order if we want customized sorting order then we should go for a Comparator interface. Comparator interface contains only one abstract method: compare() Hence it is a Functional interface.

public int compare(obj1,obj2)
returns a negative value(-) if obj1 has to come before obj2
returns a positive value(+) if obj1 has to come after obj2
returns 0 if obj1 and obj2 are equal

Collections.sort(list,Comparator) ==> meant for Customized Sorting Order

 

Example to Sort elements of ArrayList according to Default Natural Sorting Order(Ascending Order):

import java.util.ArrayList;
import java.util.Collections;

class Test {
 
	public static void main(String[] args) {
 
		ArrayList<Integer> l = new ArrayList<Integer>();
		l.add(10);
		l.add(0);
		l.add(15);
		l.add(5);
		l.add(20);
		System.out.println("Before Sorting:"+l);
		Collections.sort(l);
		System.out.println("After Sorting:"+l);
	}
}

 

Result:

Before Sorting: [10, 0, 15, 5, 20]
After Sorting: [0, 5, 10, 15, 20]

 

Example to Sort elements of ArrayList according to Customized Sorting Order(Descending Order):

import java.util.TreeSet;
import java.util.Comparator;

class MyComparator implements Comparator<Integer>{
 
	public int compare(Integer I1,Integer I2){
		return (I1>I2)?-1:(I1<I2)?1:0;
	}
}

class Test{
	
	public static void main(String[] args){
 
		TreeSet<Integer> l = new TreeSet<Integer>(new MyComparator());
		l.add(10);
		l.add(0);
		l.add(15);
		l.add(5);
		l.add(20);
		System.out.println(l);
	}
}

 

Result: [20, 15, 10, 5, 0]

 

Sorting with Lambda Expressions:

As Comparator is Functional interface, we can replace its implementation with Lambda Expression

Collections.sort(l,(I1,I2)->(I1<I2)?1:(I1>I2)?-1:0);

import java.util.ArrayList;
import java.util.Collections;

class Test{
	
	public static void main(String[] args){
 
		ArrayList<Integer> l= new ArrayList<Integer>();
		l.add(10);
		l.add(0);
		l.add(15);
		l.add(5);
		l.add(20);
		System.out.println("Before Sorting:"+l);
		Collections.sort(l,(I1,I2)->(I1<I2)?1:(I1>I2)?-1:0);
		System.out.println("After Sorting:"+l);
	}
}

 

Result:

Before Sorting:[10, 0, 15, 5, 20]
After Sorting:[20, 15, 10, 5, 0]

 

2. Sorted Set:

In the case of Set, if we want Sorting order then we should go for TreeSet

1. TreeSet t = new TreeSet();  // This TreeSet object meant for default natural sorting order

2. TreeSet t = new TreeSet(Comparator c);  // This TreeSet object meant for Customized Sorting Order

 

Example for Default Natural Sorting Order(Ascending Order):

import java.util.TreeSet;

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

		TreeSet<Integer> t = new TreeSet<Integer>();
		t.add(10);
		t.add(0);
		t.add(15);
		t.add(5);
		t.add(20);
		System.out.println(t);
	}
}

Result : [0, 5, 10, 15, 20]

 

Example of Customized Sorting Order(Descending Order):

import java.util.TreeSet;

class Test{
		
		public static void main(String[] args){
		
			TreeSet<Integer> t = new TreeSet<Integer>((I1,I2)->(I1>I2)?-1:(I1<I2)?1:0);
			t.add(10);
			t.add(0);
			t.add(15);
			t.add(25);
			t.add(5);
			t.add(20);
			System.out.println(t);
		}
}

Result: [25, 20, 15, 10, 5, 0]

 

 

3. Sorted Map:

In the case of Map, if we want default natural sorting order of keys then we should go for TreeMap.

1. TreeMap m = new TreeMap(); // This TreeMap object meant for default natural sorting order of keys

2. TreeMap t = new TreeMap(Comparator c); // This TreeMap object meant for Customized Sorting Order of keys

 

Example for Default Natural Sorting Order(Ascending Order):

import java.util.TreeMap;

class Test{
	
	public static void main(String[] args){
	
		TreeMap<Integer,String> m = new TreeMap<Integer,String>();
		m.put(100,"Fayçal");
		m.put(600,"Amine");
		m.put(300,"Azzedine");
		m.put(200,"Karim");
		m.put(700,"Halim");
		m.put(400,"Mourad");
		System.out.println(m);
	}
}

Result: {100=Fayçal, 200=Karim, 300=Azzedine, 400=Mourad, 600=Amine, 700=Halim}

 

Example of Customized Sorting Order(Descending Order):

import java.util.TreeMap;

class Test{
	
	public static void main(String[] args){
	
		TreeMap<Integer,String> m = new TreeMap<Integer,String>((I1,I2)->(I1<I2)?1:(I1>I2)?-1:0);
		m.put(100,"Fayçal");
		m.put(600,"Amine");
		m.put(300,"Azzedine");
		m.put(200,"Karim");
		m.put(700,"Halim");
		m.put(400,"Mourad");
		System.out.println(m);
	}
}

Result: {700=Halim, 600=Amine, 400=Mourad, 300=Azzedine, 200=Karim, 100=Fayçal}

 

Leave a Reply

Your email address will not be published. Required fields are marked *