Question

Write a program that sorts the content of a map by Values. Before we start, we...

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.

Homework Answers

Answer #1
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);
    }
}
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
What's wrong with this code? #Java Why I am getting error in : int BusCompare =...
What's wrong with this code? #Java Why I am getting error in : int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); public class TypeComparator implements Comparator<Type> { @Override public int compare(Type o1, Type o2) { // return o1.name.compareTo(o2.name); int NameCompare = o1.name.compareTo(o2.name); int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); // 2-level comparison using if-else block if (NameCompare == 0) { return ((BusCompare == 0) ? NameCompare : BusCompare); } else { return NameCompare; } } } public class Type implements Comparable<Type> { int id; String name; int...
Write a Java program that reads words from a text file and displays all the words...
Write a Java program that reads words from a text file and displays all the words (duplicates allowed) in ascending alphabetical order. The words must start with a letter. 1. You must use one of following Concrete class to store data from the input.txt file. Vector, Stack, ArrayList, LinkedList 2. To sort those words, you should use one of existing interface methods available in Collection or List class.
***C++ CODING*** Write a program for sorting a list of integers in ascending order using the...
***C++ CODING*** Write a program for sorting a list of integers in ascending order using the bubble sort algorithm. Requirements Implement the following functions: Implement a function called readData int *readData( )   The function returns a pointer that points to the locations with integers reading from the file data.txt. arr is a pointer for storing the integers. The function returns the number of integers. The function readData reads the list of integers from a file call data.txt into the array...
IN JAVA Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort: <-- (I need the...
IN JAVA Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort: <-- (I need the code to be written with these) I need Class river, Class CTRiver and Class Driver with comments so I can learn and better understand the code I also need a UML Diagram HELP Please! Class River describes river’s name and its length in miles. It provides accessor methods (getters) for both variables, toString() method that returns String representation of the river, and method isLong()...
Assignment #4 – Student Ranking : In this assignment you are going to write a program...
Assignment #4 – Student Ranking : In this assignment you are going to write a program that ask user number of students in a class and their names. Number of students are limited to 100 maximum. Then, it will ask for 3 test scores of each student. The program will calculate the average of test scores for each student and display with their names. Then, it will sort the averages in descending order and display the sorted list with students’...
Please do the following in python: Write a program (twitter_sort.py) that merges and sorts two twitter...
Please do the following in python: Write a program (twitter_sort.py) that merges and sorts two twitter feeds. At a high level, your program is going to perform the following: Read in two files containing twitter feeds. Merge the twitter feeds in reverse chronological order (most recent first). Write the merged feeds to an output file. Provide some basic summary information about the files. The names of the files will be passed in to your program via command line arguments. Use...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform an empirical analysis of the QuickSort algorithm to study the actual average case behavior and compare it to the mathematically predicted behavior. That is, you will write a program that counts the number of comparisons performed by QuickSort on an array of a given size. You will run the program on a large number of arrays of a certain size and determine the average...
Java Program: You will be inserting values into a generic tree, then printing the values inorder,...
Java Program: You will be inserting values into a generic tree, then printing the values inorder, as well as printing the minimum and maximum values in the tree. Given main(), write the methods in the 'BSTree' class specified by the // TODO: sections. There are 5 TODOs in all to complete. Ex: If the input is like ferment bought tasty can making apples super improving juice wine -1 the output should be: Enter the words on separate lines to insert...
c++ Program Description You are going to write a computer program/prototype to process mail packages that...
c++ Program Description You are going to write a computer program/prototype to process mail packages that are sent to different cities. For each destination city, a destination object is set up with the name of the city, the count of packages to the city and the total weight of all the packages. The destination object is updated periodically when new packages are collected. You will maintain a list of destination objects and use commands to process data in the list....
You can complete this assignment individually or as a group of two people. In this assignment...
You can complete this assignment individually or as a group of two people. In this assignment you will create a ​​Sorted Singly-Linked List​ that performs basic list operations using C++. This linked list should not allow duplicate elements. Elements of the list should be of type ‘ItemType’. ‘ItemType’ class should have a private integer variable with the name ‘value’. Elements in the linked list should be sorted in the ascending order according to this ‘value’ variable. You should create a...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT