Write a program that sorts the content of a map by Values. Before we start, we need to check the explanation of Java Map Interface and Java LinkedHashMap. This program can be implemented as follows:
1. Create a LinkedHashMap class <String (Country), String(Capital)> that stores Capitals of FIVE countries.
2. Use sortMap() for receiving content of the created class of LinkedHashMap and reorder it in a sorted Map. (sort in natural order).
3. You need to transfer the map into a list (capitalList as an example), then use the function of sort() which works with a list, and then use a comparator as explained in the next point.
4. In this program: “java.util.Comparator.compare(String o1, String o2), the comparator is the lamda which compares (o1, o2) -> o1.getValue().compareTo(o2.getValue()). // values listed in both o1 and o2.
5. Then you should get the sorted list.
6. Finally, convert the list to LinkedHashMap, then loop through all sorted items and print them out by their key and value.
*/ Java Comparator interface is used to order the objects of a user-defined class.This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).
*/ You can decide about the Name of program, classes, and data content.
import java.util.*;
import java.util.Map.Entry;
class Sortbyname implements Comparator<String>
{
// Used for sorting in ascending order of
// roll name
public int compare(String o1, String o2)
{
return o1.compareTo(o2);
}
}
public class doselect_lab7_1 {
public static void getMethod(LinkedHashMap<String,String> map)
{
List keys = new ArrayList<String>(map.keySet());
List values = new ArrayList<String>(map.values());
Collections.sort(values,new Sortbyname());
LinkedHashMap<String,String> sortedMap = new LinkedHashMap<String,String>();
for(int i=0;i<values.size();i++)
for(Entry<String,String> entry: map.entrySet())
{
if(Objects.equals(values.get(i), entry.getValue()))
sortedMap.put(entry.getKey(), entry.getValue());
}
for(Entry<String,String> entry: sortedMap.entrySet())
{
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
public static void main(String[] args) {
LinkedHashMap<String,String> m = new LinkedHashMap<String,String>();
m.put("India", "New Delhi");
m.put("Japan", "Tokya");
m.put("USA", "Washington DC");
m.put("England", "London");
m.put("France","Paris");
getMethod(m);
}
}
Get Answers For Free
Most questions answered within 1 hours.