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
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.
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’...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called keys with other objects called values. It is implemented as a Java class that uses arrays internally. 1. Theory. A map is a set of key-value pairs. Each key is said to be associated with its corresponding value, so there is at most one pair in the set with a given key. You can perform the following operations on maps. You can test if...
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...
Please answer in JAVA IDS 401 Assignment 4 Deadline In order to receive full credit, this...
Please answer in JAVA IDS 401 Assignment 4 Deadline In order to receive full credit, this assignment must be submitted by the deadline on Blackboard. Submitting your assignment early is recommended, in case problems arise with the submission process. Late submissions will be accepted (but penalized 10pts for each day late) up to one week after the submission deadline. After that, assignments will not be accepted. Assignment The object of this assignment is to construct a mini-banking system that helps...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as possible: What is a checked exception, and what is an unchecked exception? What is NullPointerException? Which of the following statements (if any) will throw an exception? If no exception is thrown, what is the output? 1: System.out.println( 1 / 0 ); 2: System.out.println( 1.0 / 0 ); Point out the problem in the following code. Does the code throw any exceptions? 1: long value...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop a class, using templates, to provide functionality for a set of recursive functions. The functions specified as recursive must be written recursively (not iterativly). The UML class specifications are provided below. A main will be provided. Additionally, a make file will need to be developed and submitted. ● Recursion Set Class The recursion set template class will implement the template functions. recursionSet -length: int...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to the method header that will be a boolean variable: public boolean add(T newEntry, boolean sorted) The modification to the add method will makeit possible toadd new entriesto the beginning of the list, as it does now, but also to add new entries in sorted order. The sorted parameter if set to false will result in the existing functionality being executed (it will add the...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code to initialize the CustomerAccountsDB database table and add a set of customer accounts is provided. Finish the code in these 3 methods in CustomerAccountDB.java to update or query the database: -purchase(double amountOfPurchase) -payment(double amountOfPayment) -getCustomerName() Hint: For getCustomerName(), look at the getAccountBalance() method to see an example of querying data from the database. For the purchase() and payment() methods, look at the addCustomerAccount() method...
IntList Lab Specifications You are required to come up with a single header file (IntList.h) that...
IntList Lab Specifications You are required to come up with a single header file (IntList.h) that declares and implements the IntNode class (just copy it exactly as it is below) as well as declares the IntList Class interface only. You are also required to come up with a separate implementation file (IntList.cpp) that implements the member functions of the IntList class. While developing your IntList class you must write your own test harness (within a file named main.cpp). Never implement...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT