Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method that accepts two LinkedLists, list1 and list2 of the same length.

ID: 3694767 • Letter: W

Question

Write a method that accepts two LinkedLists, list1 and list2 of the same length. Each List stores integers. The method should return a merged map where the keys are the elements in list1 and the values are the elements in list2 in reverse order. Thus, the key for the first element in the map is the first element in list1 and the corresponding value is the last element in list2. The key for the second element in the map is the second element in list1 and the corresponding value is the next to last element in list2, etc.

Explanation / Answer

Hello there ,

Please find below code and it's output.

import java.util.HashMap;
import java.util.LinkedList;

public class CustomMap {
   public static void main(String args[]) {
       LinkedList<Integer> list1 = new LinkedList<Integer>();
       LinkedList<Integer> list2 = new LinkedList<Integer>();
       list1.add(1);
       list1.add(2);
       list1.add(3);
       list2.add(4);
       list2.add(5);
       list2.add(6);
       System.out.println("List 1: " + list1);
       System.out.println("List 2: " + list2);
       System.out.println("HashMap: " + merge(list1, list2));
   }

   /**
   * Method that creates a hashmap and use key from list1 and put values from list2 in reverse order.
   * @param list1
   * @param list2
   * @return
   */
   public static HashMap<Integer, Integer> merge(LinkedList<Integer> list1, LinkedList<Integer> list2) {
       HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
       if (list1.size() == list2.size()) {
           for (int i = 0; i < list1.size(); i++) {
               map.put(list1.get(i), list2.get(list2.size() - 1 - i));
           }

       } else {
           System.out.println("Provided lists are not of equal size." + list1.size() + " " + list2.size());
           return null;
       }
       return map;

   }
}

===O/P==

List 1: [1, 2, 3]
List 2: [4, 5, 6]
HashMap: {1=6, 2=5, 3=4}

Let me know if you have any doubts !

Thanks.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote