Monday 1 August 2016

Sort elements of a list in predefined order

Suppose you are maintaining list of languages like below.

English
Hindi
Telugu
Sanskrit
Chinese
Japanese
French


Whatever the languages order you are getting, your sort function should sort them like the order given above. By using map kind of data structure and custom comparator, you can sort the elements in custom order.
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
 private static Map<String, Integer> map = new HashMap<>();

 static {

  map.put("English", 1);
  map.put("Hindi", 2);
  map.put("Telugu", 3);
  map.put("Sanskrit", 4);
  map.put("Chinese", 5);
  map.put("Japanese", 6);
  map.put("French", 7);

 }

 public static List<String> getSortedData(List<String> list) {
  Collections.sort(list, new Comparator<String>() {
   @Override
   public int compare(String str1, String str2) {
    return map.get(str1) - map.get(str2);
   }
  });
  return list;
 }

 public static void main(String args[]) {
  List<String> list1 = Arrays.asList("English", "Hindi", "Telugu", "Sanskrit", "Chinese", "Japanese", "French");

  List<String> list2 = Arrays.asList("Chinese", "Japanese", "French", "English", "Hindi", "Telugu", "Sanskrit");

  List<String> list3 = Arrays.asList("English", "Hindi", "Chinese", "Japanese", "French", "Telugu", "Sanskrit");

  System.out.println(getSortedData(list1));
  System.out.println(getSortedData(list2));
  System.out.println(getSortedData(list3));

 }
}


Output
[English, Hindi, Telugu, Sanskrit, Chinese, Japanese, French]
[English, Hindi, Telugu, Sanskrit, Chinese, Japanese, French]
[English, Hindi, Telugu, Sanskrit, Chinese, Japanese, French]

No comments:

Post a Comment