Java ConcurrentSkipListMap Sort by Value

By Arvind Rai, December 19, 2022
On this page, we will learn to sort ConcurrentSkipListMap by its value.
1. The ConcurrentSkipListMap implements concurrent variant of SkipLists. The methods of ConcurrentSkipListMap such as containsKey, get, put and remove have expected average log(n) time cost.
2. The ConcurrentSkipListMap supports concurrency. Insertion, removal, update, and access operations safely execute concurrently by multiple threads.
3. To sort the ConcurrentSkipListMap, we can convert them into Stream and then use its sorted() method.

Using stream() method

1. With Map.Entry.comparingByValue() .
ConcurrentSkipListMap<Integer, String> map = new ConcurrentSkipListMap<>();
map.put(1, "Mahesh");
map.put(2, "Anil");
map.put(3, "Suresh");
map.put(4, "Krishn");

Stream<Map.Entry<Integer, String>> sorted = map.entrySet().stream()
		   .sorted(Map.Entry.comparingByValue());
sorted.forEach(s -> System.out.println(s)); 
Output
2=Anil
4=Krishn
1=Mahesh
3=Suresh 
2. Reversing the sorting order using Collections.reverseOrder .
Stream<Map.Entry<Integer, String>> sorted = map.entrySet().stream()
		   .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
sorted.forEach(s -> System.out.println(s)); 
Output
3=Suresh
1=Mahesh
4=Krishn
2=Anil 
3. Using Comparator .
ComparatorMain.java
package com.concretepage;
import java.io.IOException;
import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.stream.Stream;

public class ComparatorMain {
  public static void main(String... args) throws Exception, IOException {
	ConcurrentSkipListMap<Integer, Person> map = new ConcurrentSkipListMap<>();
	map.put(1, new Person("Mahesh", 25));
	map.put(2, new Person("Anil", 30));
	map.put(3, new Person("Suresh", 23));
	map.put(4, new Person("Krishn", 27));
	
	Comparator<Person> personComparator = Comparator.comparing(Person::getName);
	
	Stream<Map.Entry<Integer, Person>> sorted = map.entrySet().stream()
	           .sorted(Map.Entry.comparingByValue(personComparator));
	sorted.forEach(s -> System.out.println(s));
  }
}

class Person {
  private String name;
  private int age;
  public Person(String name, int age) {
	this.name = name;
	this.age = age;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  @Override
  public String toString() {
    return name + " - " + age; 
  }
} 
Output
2=Anil - 30
4=Krishn - 27
1=Mahesh - 25
3=Suresh - 23 
We can reverse the order using reversed() method of Comparator.
Stream<Map.Entry<Integer, Person>> sorted = map.entrySet().stream()
           .sorted(Map.Entry.comparingByValue(personComparator.reversed())); 

Reference

Class ConcurrentSkipListMap
POSTED BY
ARVIND RAI
ARVIND RAI











©2023 concretepage.com | Privacy Policy | Contact Us