Skip to main content

Java 8- Sorting Collections using lambda expression


Java 7 (old way)-
1. Create a comparator
2. Use Collections.sort or pass the comparator to constructor if you are using treeset or treemap
3. Use the comparator
a)     Option 1- Pass comparator as argument- Collections.sort(collection, comparator);
b)     Option 2- Keep collection sorted always
TreeSet<Integer> treeset = new TreeSet<>(comparator);
TreeMap<Integer, String> treemap = new TreeMap<>(comparator);
Below are few examples- note this can be done only for collections which maintain the sorting order and at the time of initialization you don’t default sorting or order but some custom sorting order. Below is an example of one of the constructors which directly accepts a comparator

Java 8- Using lambda expressions

As comparator is a functional interface (consists of single abstract method), we can use lambda expression to create the sorting expression. Below is Lamda expression for sorting a list in ascending order
(i1, i2) -> (i1-i2)
// for integers
Ascending sort- Collection.sort (col, (i1, i2) -> (i1-i2)); // follow regular sequence 1st & then 2nd
Descending sort- Collection.sort (col, (i1, i2) -> (i2-i1)); //Reverse the sequence, 2nd & then 1st
// for strings
Ascending sort- Collection.sort (col, (s1, s2) -> (s1.compareTo(s2)); // follow regular sequence 1st & then 2nd
Descending sort- Collection.sort (col, (s1, s2) -> (s2.compareTo(s1)); //Reverse the sequence, 2nd & then 1st

Comments

Popular posts from this blog

Java 8- Sorting a hashmap (by key and by value) using lambda expression and streams

Sometimes while working on business problems, it’s very common to come across use cases wherein a map needs to be sorted by either keys or by values. In this post, we will cover some of the examples to sort a map of primitives and custom objects.   In below approaches, we will not destroy existing map and will create a new map to ensure consistency of sorting 1. Sort HashMap by key  In order to sort a map by key, all we need to do is to use sorted method of stream interface and pass a default default/custom comparator to it. Moreover, to sort by keys, we need to use comparingByKey method of Entry interface of Map. 2. Sort HashMap by values  In order to sort a map by key, all we need to do is to use sorted method of stream interface and pass a default default/custom comparator to it. Moreover, to sort by keys, we need to use comparingByValue method of Entry interface of Map.

Walls and gates- Find shortest distances between rooms and gates

Leetcode: Walls and Gates You are given a  m x n  2D grid initialized with these three possible values. -1  - A wall or an obstacle. 0  - A gate. INF  - Infinity means an empty room. We use the value  2 31  - 1 = 2147483647  to represent  INF  as you may assume that the distance to a gate is less than 2147483647 . Fill each empty room with the distance to its  nearest  gate. If it is impossible to reach a gate, it should be filled with  INF . For example, given the 2D grid: INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF After running your function, the 2D grid should be: 3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4 Understand the problem: It is very classic backtracking problem. We can start from each gate (0 point), and searching for its neighbors. We can either use DFS or BFS solution. Below is a DFS solution-

Design LRU Cache

Design and implement a data structure for  Least Recently Used (LRU) cache . It should support the following operations:  get  and  put . get(key)  - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value)  - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. Follow up: Could you do both operations in  O(1)  time complexity? Example: LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1);        // returns 1 cache.put(3, 3);      // evicts key 2 cache.get(2);        // returns -1 (not found) cache.put(4, 4);     // evicts key 1 cache.get(1);        //...