Java Lambda Expression with Collections


Sorting the elements of a list using lambda expression

Example

 Live Demo

import java.util.*;
public class Demo{
   public static void main(String[] args){
      ArrayList<Integer> my_arr = new ArrayList<Integer>();
      my_arr.add(190);
      my_arr.add(267);
      my_arr.add(12);
      my_arr.add(0);
      System.out.println("Before sorting, elements in the array list are : " + my_arr);
      Collections.sort(my_arr, (o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0);
      System.out.println("After sorting, elements in the array list are : " + my_arr);
   }
}

Output

Before sorting, elements in the array list are : [190, 267, 12, 0]
After sorting, elements in the array list are : [267, 190, 12, 0]

A class named Demo contains the main function. Here, an arraylist is created and elements are added into it using the ‘add’ function. The elements are sorted using the sort function and a conditional expression decided what has to be displayed on the screen depending on whether the elements are less than or greater than or equal to each other.

Sorting the elements of a treemap using lambda expression

Example

 Live Demo

import java.util.*;
public class Demo{
   public static void main(String[] args){
      TreeMap<Integer, String> my_treemap = new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ? -1 :       (o1 < o2) ? 1 : 0);
      my_treemap.put(56, "Joe");
      my_treemap.put(43, "Bill");
      my_treemap.put(21, "Charolette");
      my_treemap.put(33, "Jonas");
      System.out.println("The treemap contains the following elements : " + my_treemap);
   }
}

Output

The treemap contains the following elements : {56=Joe, 43=Bill, 33=Jonas, 21=Charolette}

A class named Demo contains the main function. Here, a treemap is defined, and conditional expression is also written here. Elements are added into the treemap using the ‘put’ function and they are printed on the console.

Updated on: 04-Jul-2020

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements