Collections Framework: past questions

32 questions · 166 marks · 8 papers. Try each one before checking.

Solve them and check answers →Read the notes first

2023 Aug

Question 9 MCQ · 3 marks

Consider the Java code given below.

import java.util.*;
public class MapTest{
    public static void printPlayers(Map<String, Integer> m){
        var map1 = new LinkedHashMap<String, Integer>();
        var map2 = new TreeMap<String, Integer>();
        String[] players = {"Buttler", "Roy", "Dhoni"};
        for(String p : players){
            map1.put(p, m.getOrDefault(p, 0));
            map2.put(p, m.getOrDefault(p, 0));
        }
        System.out.println(map1);
        System.out.println(map2);
    }
    public static void main(String[] args){
        var map = new HashMap<String, Integer>();
        map.put("Roy", 78);
        map.put("Surya", 56);
        map.put("Buttler", 14);
        printPlayers(map);
    }
}

What will the output be? You may make use of the method description given below. getOrDefault(Object key, V defaultValue): Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

  1. {Buttler=14, Dhoni=0, Roy=78}
    {Buttler=14, Roy=78, Dhoni=0}
  2. {Buttler=14, Roy=78, Dhoni=0, Surya=56}
    {Buttler=14, Dhoni=0, Roy=78, Surya=56}
  3. {Buttler=14, Roy=78, Dhoni=0}
    {Buttler=14, Dhoni=0, Roy=78}
  4. {Buttler=14, Roy=78, Dhoni=0, Surya=0}
    {Buttler=14, Dhoni=0, Roy=78, Surya=0}

Question 7 MCQ · 3 marks

Consider the Java code given below.

import java.util.*;
class Student{
    String name;
    double cgpa;
    //Constructor to initialize name and cgpa
    public String toString() {
        return name;
    }
}
public class IteratorTest {
    public static boolean property(double x) {
        if(x < 7.0)
            return false;
        return true;
    }
    public static List<Student> getFinalList(List<Student> sList){
        Iterator<Student> it = sList.iterator();
        while (it.hasNext()) {
            Student s = it.next();
            if(!property(s.cgpa))
                ______________________________ //LINE 1
        }
        return sList;
    }
    public static void main(String[] args) {
        var list = new ArrayList<Student>();
        list.add(new Student("Sandeep", 9.78));
        list.add(new Student("Navadeep", 5.78));
        list.add(new Student("Randeep", 7.0));
        list.add(new Student("Gunadeep", 7.0));
        System.out.println(getFinalList(list));
    }
}

Choose the correct option to be filled in place of LINE 1 so that the output is: [Sandeep, Randeep, Gunadeep]

  1. it.remove(s)

  2. it.remove()

  3. sList.remove()

  4. sList.remove(s)

Question 16 MCQ · 4 marks

Consider the Java code given below.

import java.util.*;
public class SetExample {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("Python");
        list.add("Programming");
        list.add("Java");
        list.add("Programming");

        Set<String> set1 = new LinkedHashSet<String>();
        Set<String> set2 = new TreeSet<String>();
        for(String str : list) {
            set1.add(str);
            set2.add(str);
        }
        for(String str : set1) {
            System.out.print(str + " ");
        }
        System.out.println();
        for(String str : set2) {
            System.out.print(str + " ");
        }
    }
}

What will the output be?

  1. Java Programming Python
    Python Programming Java
  2. Python Programming Java
    Java Programming Python
  3. Python Programming Programming Java
    Java Programming Programming Python
  4. Java Programming Programming Python
    Python Programming Programming Java

Question 10 MCQ · 3 marks

Consider the Java code given below that checks whether the input number is a palindrome or not.

import java.util.*;
public class QTest {
    public static boolean checkPalindrome(Deque<Character> q) {
        //CODE BLOCK
        return q.isEmpty();
    }
    public static void main(String[] args) {
        String num1 = "34543";
        String num2 = "12312";
        Deque<Character> q1 = new ArrayDeque<Character>();
        Deque<Character> q2 = new ArrayDeque<Character>();
        for(int i = 0; i < 5; i++) {
            q1.add(num1.charAt(i));
            q2.add(num2.charAt(i));
        }
        System.out.println(checkPalindrome(q1));
        System.out.println(checkPalindrome(q2));
    }
}

Choose the correct option(s) to fill in place of CODE BLOCK so that the output is:

true
false

You may make use of the descriptions of the methods given below. These are methods inside type Deque.

  1. if(q.size() > 0) {
        if(q.poll() != q.pollLast())
            break;
    }
  2. while(q.size() < 0) {
        if(q.poll() != q.pollLast())
            break;
    }
  3. while(q.size() > 0) {
        if(q.poll() != q.pollLast())
            break;
    }
  4. if(q.size() > 0) {
        while(q.poll() != q.pollLast())
            break;
    }

2023 Dec

Question 8 MCQ · 3 marks

Consider the Java code given below.

import java.util.*;
class Student {
    String name, subject;
    int marks;
    public Student(String n, String s, int m){
        name = n;
        subject = s;
        marks = m;
    }
}
public class Test{
    public static void printStudents(ArrayList<Student> sL) {
        var map = new LinkedHashMap<String, Integer>();
        for(Student s : sL) {
            map.put(s.name, map.getOrDefault(s.name, 0) + s.marks);
        }
        for(Map.Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
        }
    }
    public static void main(String[] args) {
        ArrayList<Student> sList = new ArrayList<Student>();
        sList.add(new Student("Carl", "Maths", 80));
        sList.add(new Student("Rayan", "Maths", 89));
        sList.add(new Student("Lokesh", "Social", 100));
        sList.add(new Student("Carl", "Science", 98));
        printStudents(sList);
    }
}

What will the output be?

  1. Carl = 98
    Rayan = 89
    Lokesh = 100
  2. Carl = 178
    Lokesh = 100
    Rayan = 89
  3. Carl = 178
    Rayan = 89
    Lokesh = 100
  4. Carl = 80
    Lokesh = 100
    Rayan = 89

Question 11 MCQ · 4 marks

Consider the Java code given below.

import java.util.*;
class Candidate{
    String name;
    int aptitudeScore;
    //Constructor to initialize the instance variables
    public String toString(){
        return name;
    }
}
public class Test{
    public static boolean check(int aptitudeScore){
        if (aptitudeScore > 75)
            return true;
        return false;
    }
    public static void printShortlistCdtList(List<Candidate> cList) {
        Iterator<Candidate> it = cList.iterator();
        while (it.hasNext()){
            Candidate c = it.next();
            if(!check(c.aptitudeScore))
                it.remove();
        }
    }
    public static void main(String[] args) {
        var list = new ArrayList<Candidate>();
        list.add(new Candidate("Meena", 89));
        list.add(new Candidate("Manu", 40));
        list.add(new Candidate("Payal", 68));
        list.add(new Candidate("Ayan", 78));
        printShortlistCdtList(list);
        System.out.println(list);
    }
}

Choose the correct option.

  1. This program generates the output: [Ayan, Meena]

  2. This program generates the output: [Manu, Payal]

  3. This program generates the output: [Meena, Ayan]

  4. This program generates the output: [Ayan, Manu, Meena, Payal]

Question 2 MCQ · 3 marks

Consider the Java code given below.

import java.util.*;
public class SetIteratorTest {
    public static void main(String[] args) {
        var set1 = new HashSet<String>();
        set1.add("Cherry");
        set1.add("Banana");
        set1.add("Apple");
        set1.add("Date");

        var set2 = new TreeSet<String>(set1);
        Iterator<String> it1 = set1.iterator();
        Iterator<String> it2 = set2.iterator();

        while (it1.hasNext()) {
            System.out.println(it1.next());
        }

        while (it2.hasNext()) {
            System.out.println(it2.next());
        }
    }
}

Choose the correct option.

  1. it1 will visit elements of set1 in sorted order. it2 will visit elements of set2 in sorted order.

  2. it1 will visit elements of set1 in the order in which they were inserted. it2 will visit elements of set2 in sorted order.

  3. it1 will visit elements of set1 in unspecified order. it2 will visit elements of set2 in sorted order.

  4. it1 will visit elements of set1 in the order in which they were inserted. it2 will visit elements of set2 in unspecified order.

Question 9 MCQ · 3 marks

Consider the following code.

import java.util.*;
public class TreeTest {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Monkey");
        list.add("Lion");
        list.add("Goat");
        list.add("Elephant");
        HashSet<String> set1 = new HashSet<String>(list);
        TreeSet<String> set2 = new TreeSet<String>(set1);
        set2.addAll(set1);
        System.out.println(set2);
    }
}

Choose the correct option.

  1. This program generates the output: [Elephant, Goat, Lion, Monkey, Elephant, Goat, Lion, Monkey]

  2. This program generates the output: [Elephant, Goat, Lion, Monkey]

  3. This program terminates abnormally due to UnsupportedOperationException.

  4. This program generates the output: []

Question 14 MSQ · 3 marks

Consider the Java code given below.

import java.util.*;
class Test {
    public static String search(Deque<Integer> q, int num) {
        while(q.size() > 0) {
            // LINE 1
            {
                return "Element found";
            }
        }
        return "Element not found";
    }
    public static void main(String[] args) {
        Deque<Integer> queue1 = new ArrayDeque<Integer>();
        queue1.add(60);
        queue1.add(36);
        queue1.add(96);
        queue1.add(70);
        System.out.println(search(queue1, 96));
    }
}

Identify the appropriate option(s) to fill in place of LINE 1 such that the output is: Element found

  1. if(q.peek() == num)

  2. if(q.element() == num)

  3. if(q.poll() == num)

  4. if(q.remove() == num)

2024 Mar 24

Question 6 MCQ · 6 marks

Consider the following code.

import java.util.*;
public class Test {
    public static void main(String[] args) {
        List<Integer> scores1 = new ArrayList<>();
        scores1.add(34);
        scores1.add(42);
        scores1.add(50);

        List<Integer> scores2 = new ArrayList<>();
        scores2.add(45);
        scores2.add(90);
        scores2.add(34);

        Map<String, Integer> am = new HashMap<>();
        Map<String, List<Integer>> hm = new HashMap<>();
        hm.put("Anil", scores1);
        hm.put("Vikas", scores2);
        Set<String> names = hm.keySet();
        for(String name : names){
            List<Integer> temp = hm.get(name);
            int count = 0;
            int sum = 0;
            ***----------------***
                  CODE BLOCK
            ***----------------***
            int avg = sum/count;
            am.put(name, avg);
        }
    }
}

Choose the correct option to fill in the CODE BLOCK to add the name and the average scores of both the students as map entries in Map<String, Integer> am.

  1. for(List i : temp){
        count = count + 1;
        sum = sum + i;
    }
  2. for(List<Integer> i : temp){
        count = count + 1;
        sum = sum + i;
    }
  3. for(int i : temp){
        sum = sum + temp;
        count = count + 1;
    }
  4. for(Integer i : temp){
        count = count + 1;
        sum = sum + i;
    }

Question 13 MCQ · 7 marks

Consider the Java code given below.

import java.util.*;
class Contestant {
    String name;
    int points;
    //constructor to initialize name and points
    public String toString() {
        return name;
    }
}
public class IteratorTest {
    public static boolean ranked(int x) {
        if(x < 5)
            return false;
        return true;
    }
    public static void getFinalList(List<Contestant> cList){
        Iterator<Contestant> it = cList.iterator();
        while (it.hasNext()) {
            Contestant c = it.next();
            if(!ranked(c.points))
                ______________________________ //LINE 1
        }
    }
    public static void main(String[] args) {
        var list = new ArrayList<Contestant>();
        list.add(new Contestant("Sanju", 7));
        list.add(new Contestant("Kiran", 4));
        list.add(new Contestant("Ram", 5));
        list.add(new Contestant("John", 5));
        getFinalList(list);
        System.out.println(list);
    }
}

Choose the correct option to be filled in place of LINE 1 so that the output is: [Sanju, Ram, John]

  1. it.remove(c)

  2. it.remove()

  3. cList.remove()

  4. cList.remove(c)

Question 5 MCQ · 6 marks

The following code maps a set of names of employees to their performance ratings, and groups the names based on their eligibility for bonus. Based on the code, answer the question that follows.

import java.util.*;
public class Employee {
    TreeSet<String> t1 = new TreeSet<String>();
    TreeSet<String> t2 = new TreeSet<String>();
    public boolean PerformanceRating(double rating) {
        if(rating >= 4.0){
            return true;
        }
        return false;
    }
    public void filterEmployees(TreeMap<String, Double> rating) {
        for (Map.Entry<String, Double> entry : rating.entrySet()) {
            if (PerformanceRating(entry.getValue())) {
                t1.add(entry.getKey());
            } else {
                t2.add(entry.getKey());
            }
        }
    }
    public void display() {
        System.out.println("Eligible for Bonus: " + t1);
        System.out.println("Not Eligible for Bonus: " + t2);
    }
    public static void main(String[] args) {
        TreeMap<String, Double> rating = new TreeMap<String, Double>();
        rating.put("Ramesh", 4.5);
        rating.put("Suresh", 3.8);
        rating.put("Kartik", 4.2);
        rating.put("Shubham", 3.5);
        rating.put("Mukesh", 4.8);
        Employee e = new Employee();
        e.filterEmployees(rating);
        e.display();
    }
}

Choose the correct option.

  1. This program generates the output:

    Eligible for Bonus: [Shubham, Suresh]
    Not Eligible for Bonus: [Mukesh, Ramesh, Kartik]
  2. This program generates the output:

    Eligible for Bonus: [Kartik, Mukesh, Ramesh]
    Not Eligible for Bonus: [Shubham, Suresh]
  3. This program generates the output:

    Eligible for Bonus: [Mukesh, Ramesh, Kartik]
    Not Eligible for Bonus: [Shubham]
  4. The order in which elements of t1 and t2 are printed cannot be predicted.

Question 7 MCQ · 6 marks

Consider the Java code given below that checks whether the input word is a palindrome or not.

import java.util.*;
public class PalindromeChecker {
    public static boolean isPalindrome(String word) {
        Deque<Character> deque = new ArrayDeque<>();
        for (int i = 0; i < word.length(); i++) {
            deque.add(word.charAt(i));
        }
        //CODE BLOCK
        return true;
    }
    public static void main(String[] args) {
        String word1 = "radar";
        String word2 = "hello";
        System.out.println("Is '" + word1 + "' a palindrome? " + isPalindrome(word1));
        System.out.println("Is '" + word2 + "' a palindrome? " + isPalindrome(word2));
    }
}

Choose the correct option(s) to fill in place of CODE BLOCK so that the output is:

Is 'radar' a palindrome? true
Is 'hello' a palindrome? false

Please note the following methods from type Deque.

  1. while (deque.size() > 0) {
        if (deque.pollFirst() != deque.pollLast()) {
            return true;
        }
    }
  2. while (deque.size() < 0) {
        if (deque.pollFirst() != deque.pollLast()) {
            return false;
        }
    }
  3. while (deque.size() > 1) {
        if (deque.pollFirst() != deque.pollLast()) {
            return false;
        }
    }
  4. while (deque.size() > 0) {
        char first = deque.pollFirst();
        char last = deque.pollLast();
        if (first != last) {
            return true;
        }
    }

2024 Aug 04

Question 5 MCQ · 6 marks

Consider the Java code given below.

import java.util.*;
public class Test {
    public static void main(String[] args) {
        Map<String, Integer> match1 = new TreeMap<String, Integer>();
        match1.put("Sachin", 100);
        match1.put("Virat", 75);
        match1.put("Dhoni", 50);
        match1.put("Rohit", 120);

        Map<String, Integer> match2 = new TreeMap<String, Integer>();
        match2.put("Sachin", 80);
        match2.put("Virat", 90);
        match2.put("Dhoni", 60);
        match2.put("Rohit", 110);

        Map<String, Integer> totalRuns = new TreeMap<String, Integer>();
        for (Map.Entry<String, Integer> m1 : match1.entrySet())
            totalRuns.put(m1.getKey(), m1.getValue());
        for (Map.Entry<String, Integer> m2 : match2.entrySet())
            totalRuns.merge(m2.getKey(), m2.getValue(), Integer::sum); //LINE 1
        System.out.println(totalRuns);
    }
}

Choose the correct option.

  1. LINE 1 generates compilation error because of invalid key.

  2. This program generates the output: {Dhoni=110, Rohit=230, Sachin=180, Virat=165}

  3. This program generates the output: {Sachin=180, Virat=165, Dhoni=110, Rohit=230}

  4. This program generates the output: {Virat=165, Sachin=180, Rohit=230, Dhoni=110}

Question 14 MCQ · 7 marks

Consider the Java code given below.

import java.util.*;
public class MapTest {
    public static void printPlayers(Map<String, Integer> m) {
        var map1 = new LinkedHashMap<String, Integer>();
        var map2 = new TreeMap<String, Integer>();
        String[] players = {"Virat", "Rohit", "Rahul"};
        for (String p : players) {
            if (m.containsKey(p)) {
                map1.put(p, m.get(p));
                map2.put(p, m.get(p));
            } else {
                map1.put(p, 0);
                map2.put(p, 0);
            }
        }
        System.out.println(map1);
        System.out.println(map2);
    }
    public static void main(String[] args) {
        var map = new HashMap<String, Integer>();
        map.put("Rohit", 45);
        map.put("Rahul", 60);
        map.put("Virat", 100);
        map.put("Pant", 32);
        printPlayers(map);
    }
}

What will the output be?

  1. {Virat=100, Rahul=60, Rohit=45}
    {Rahul=60, Rohit=45, Virat=100}
  2. {Virat=100, Rohit=45, Pant=32}
    {Rohit=45, Virat=100, Pant=32}
  3. {Virat=100, Rohit=45, Rahul=60, Pant=32}
    {Rohit=45, Virat=100, Rahul=60, Pant=32}
  4. {Virat=100, Rohit=45, Rahul=60}
    {Rahul=60, Rohit=45, Virat=100}

Question 12 MCQ · 7 marks

Consider the Java code given below.

import java.util.*;
class Player {
    String nickname;
    int score;
    boolean isPremium;
    //Constructor to initialize instance variables
    public String toString() {
        return nickname;
    }
}
public class GameLobby {
    public static boolean isEligible(int score, boolean isPremium) {
        if (isPremium) {
            return true;
        }
        return (score >= 10);
    }
    public static void filterPlayers(List<Player> players) {
        ListIterator<Player> iterator = players.listIterator();
        while (iterator.hasNext()) {
            Player p = iterator.next();
            if (!isEligible(p.score, p.isPremium))
                ______________________________ // LINE 1
        }
    }
    public static void main(String[] args) {
        var players = new LinkedList<Player>();
        players.add(new Player("Sharon", 15, false));
        players.add(new Player("Rohit", 8, false));
        players.add(new Player("Arjun", 20, true));
        players.add(new Player("Ambani", 9, true));
        filterPlayers(players);
        System.out.println(players);
    }
}

Choose the correct option to be filled in place of LINE 1 so that the output is: [Sharon, Arjun, Ambani]

  1. iterator.remove(p);

  2. iterator.remove();

  3. players.remove();

  4. players.remove(p);

Question 6 MCQ · 6 marks

Consider the Java code given below.

import java.util.*;
public class SequenceChecker {
    public static boolean isMirroredSequence(List<Integer> sequence) {
        Stack<Integer> s1 = new Stack<>();
        Deque<Integer> q1 = new ArrayDeque<>();
        for (int num : sequence) {
            s1.push(num);
            q1.add(num);
        }
        // CODE BLOCK
        return true;
    }
    public static void main(String[] args) {
        List<Integer> sequence1 = Arrays.asList(1, 2, 3, 2, 1);
        List<Integer> sequence2 = Arrays.asList(1, 2, 3, 4, 5);
        System.out.println("Is sequence1 mirrored? " + isMirroredSequence(sequence1));
        System.out.println("Is sequence2 mirrored? " + isMirroredSequence(sequence2));
    }
}

Choose the correct option(s) to fill in place of CODE BLOCK so that the output is:

Is sequence1 mirrored? true
Is sequence2 mirrored? false

Please note the following methods from type Stack and Deque.

  1. while (!s1.isEmpty()) {
        if (s1.pop().equals(q1.peek())) {
            return false;
        }
    }
  2. while (!s1.isEmpty()) {
        if (s1.pop().equals(q1.poll())) {
            return false;
        }
    }
  3. while (!s1.isEmpty()) {
        if (!s1.pop().equals(q1.poll())) {
            return false;
        }
    }
  4. while (!s1.isEmpty()) {
        if (!s1.pop().equals(q1.peek())) {
            return false;
        }
    }

2025 Mar 16

Question 6 MCQ · 6 marks

Consider the following Java code.

import java.util.*;
class Artist {
    String name;
    int experience;
    // Constructor to initialize instance variables
    public Artist(String n, int e) {
        name = n;
        experience = e;
    }
    public String toString() {
        return name;
    }
}
public class Test {
    public static void modifyArtistList(List<Artist> artistList) {
        ListIterator<Artist> it = artistList.listIterator();
        while (it.hasNext()) {
            Artist a = it.next();
            if (a.experience < 5) {
                //LINE 1
            }
        }
    }
    public static void main(String[] args) {
        var artists = new ArrayList<Artist>();
        artists.add(new Artist("Tagore", 12));
        artists.add(new Artist("Sudha", 3));
        artists.add(new Artist("Amitabh", 7));
        artists.add(new Artist("Sharukh", 5));
        modifyArtistList(artists);
        System.out.println(artists);
    }
}

Choose the correct option to be filled in place of LINE 1 so that the output is: [Tagore, Amitabh, Sharukh]

  1. it.remove(a)

  2. aList.remove()

  3. it.remove()

  4. aList.remove(a)

Question 4 MCQ · 6 marks

The following code maps a set of patients to the number of visits they have made to a hospital and categorizes the patients based on whether they are regular visitors (more than 3 visits) or occasional visitors.

import java.util.*;
public class Hospital {
    TreeSet<String> rPatients = new TreeSet<String>();
    TreeSet<String> oPatients = new TreeSet<String>();

    public boolean check(int visits) {
        return visits > 3;
    }

    public void categorizePatients(HashMap<String, Integer> pMap) {
        for (Map.Entry<String, Integer> entry : pMap.entrySet()) {
            if (check(entry.getValue())) {
                rPatients.add(entry.getKey());
            } else {
                oPatients.add(entry.getKey());
            }
        }
    }

    public void displayPatients() {
        System.out.println("R Patients: " + rPatients);
        System.out.println("O Patients: " + oPatients);
    }

    public static void main(String[] args) {
        HashMap<String, Integer> pMap = new HashMap<String, Integer>();
        pMap.put("James", 5);
        pMap.put("Ram", 2);
        pMap.put("Aisha", 4);
        pMap.put("Tanya", 1);
        pMap.put("Iva", 3);
        Hospital hospital = new Hospital();
        hospital.categorizePatients(pMap);
        hospital.displayPatients();
    }
}

Choose the correct option.

  1. This program generates the output:

    R Patients: [Ram, Tanya, Iva]
    O Patients: [Aisha, James]
  2. This program generates the output:

    R Patients: [Iva, James]
    O Patients: [Aisha, Ram, Tanya]
  3. This program generates the output:

    R Patients: [Aisha, James]
    O Patients: [Iva, Ram, Tanya]
  4. The order in which elements of rPatients and oPatients are printed cannot be predicted.

Question 13 MCQ · 7 marks

Consider the Java code given below.

import java.util.*;
public class SetExample {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("Apple");
        list.add("Samsung");
        list.add("Nokia");
        list.add("Samsung");

        Set<String> set1 = new LinkedHashSet<String>();
        Set<String> set2 = new TreeSet<String>();
        for (String str : list) {
            set1.add(str);
            set2.add(str);
        }
        for (String str : set1) {
            System.out.print(str + " ");
        }
        System.out.println();
        for (String str : set2) {
            System.out.print(str + " ");
        }
    }
}

What will the output be?

  1. Apple Samsung Nokia
    Apple Nokia Samsung
  2. Apple Nokia Samsung Samsung
    Nokia Samsung Apple
  3. Apple Samsung Nokia
    Samsung Nokia Apple
  4. Nokia Samsung Apple
    Apple Nokia Samsung

2026 Apr 06

Question 1 MCQ · 6 marks

Consider the Java code given below.

import java.util.*;
class SensorReading {
    String sensorId;
    String location;
    int packets;
    public SensorReading(String id, String loc, int p) {
        sensorId = id;
        location = loc;
        packets = p;
    }
}
public class Test {
    public static void printReadings(ArrayList<SensorReading> rList) {
        var map = new LinkedHashMap<String, Integer>();
        for (SensorReading s : rList) {
            map.put(s.sensorId, map.getOrDefault(s.sensorId, 0) + s.packets);
        }
        for (Map.Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
        }
    }
    public static void main(String[] args) {
        ArrayList<SensorReading> rList = new ArrayList<SensorReading>();
        rList.add(new SensorReading("TEMP01", "Lab-A", 1500));
        rList.add(new SensorReading("HUMID02", "Lab-B", 2000));
        rList.add(new SensorReading("AIRQ03", "Lab-C", 1200));
        rList.add(new SensorReading("TEMP01", "Lab-A", 800));
        printReadings(rList);
    }
}

What will the output be?

  1. TEMP01 = 800
    HUMID02 = 2000
    AIRQ03 = 1200
  2. TEMP01 = 2300
    HUMID02 = 2000
    AIRQ03 = 1200
  3. AIRQ03 = 1200
    HUMID02 = 2000
    TEMP01 = 2300
  4. HUMID02 = 2000
    AIRQ03 = 1200
    TEMP01 = 2300

Question 8 MCQ · 7 marks

The merge(K key, V value, remappingFunction) function is defined as: If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. Consider the Java code given below.

import java.util.*;
public class TelescopeReadings {
    public static void main(String[] args) {
        Map<String, Integer> observatoryA = new TreeMap<>();
        observatoryA.put("Andromeda", 88);
        observatoryA.put("Betelgeuse", 76);
        observatoryA.put("Cygnus", 92);

        Map<String, Integer> observatoryB = new TreeMap<>();
        observatoryB.put("Betelgeuse", 80);
        observatoryB.put("Cygnus", 85);
        observatoryB.put("Draco", 70);

        Map<String, Integer> merged = new TreeMap<>();
        for (Map.Entry<String, Integer> e : observatoryA.entrySet())
            merged.put(e.getKey(), e.getValue()); //LINE 1

        for (Map.Entry<String, Integer> e : observatoryB.entrySet())
            merged.merge(e.getKey(), e.getValue(),
                (oldVal, newVal) -> Math.min(oldVal, newVal));

        System.out.println(merged);
    }
}

Choose the correct option.

  1. LINE 1 generates a compilation error due to duplicate keys.

  2. {Andromeda=88, Betelgeuse=76, Cygnus=85, Draco=70}

  3. {Andromeda=88, Betelgeuse=80, Cygnus=92, Draco=70}

  4. {Andromeda=88, Betelgeuse=156, Cygnus=177, Draco=70}

Question 15 MSQ · 7 marks

Consider the code given below. HashMap m maps each element of ArrayList list to its frequency of occurrence in list.

import java.util.*;
public class Example {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(1);
        list.add(2);
        list.add(3);
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        // ------------ SEGMENT 1 ------------
        for (HashMap.Entry<Integer, Integer> entry : m.entrySet()){
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
    }
}

Identify the appropriate option(s) to fill in the blank at SEGMENT 1, such that the output is:

Key = 1, Value = 2
Key = 2, Value = 1
Key = 3, Value = 1
  1. for (Integer i : list){
        m.merge(i, 0, m.get(i) + 1);
    }
  2. for (Integer i : list){
        m.put(i, m.get(i) + 1);
    }
  3. for (Integer i : list){
        m.put(i, m.getOrDefault(i, 0) + 1);
    }
  4. for (Integer i : list){
        if(m.containsKey(i)){
            m.put(i, m.get(i) + 1);
        }
        else{
            m.put(i, 1);
        }
    }

Question 11 MCQ · 7 marks

Consider the Java code given below.

import java.util.*;
public class Test {
    public static boolean isPalindrome(String str) {
        Stack<Character> s = new Stack<>();
        Deque<Character> d = new ArrayDeque<>();
        for (char ch : str.toCharArray()) {
            s.push(ch);
            d.add(ch);
        }
        // CODE BLOCK
        return true;
    }
    public static void main(String[] args) {
        String cmd1 = "LRRL";
        String cmd2 = "LRLL";
        System.out.println("Is cmd1 a palindrome? " + isPalindrome(cmd1));
        System.out.println("Is cmd2 a palindrome? " + isPalindrome(cmd2));
    }
}

Choose the correct option to fill in place of CODE BLOCK so that the output is:

Is cmd1 a palindrome? true
Is cmd2 a palindrome? false

Please note the following methods from types Stack and Deque:

  1. while (!s.isEmpty()) {
        if (s.pop().equals(d.peek())) {
            return false;
        }
    }
  2. while (!s.isEmpty()) {
        if (s.pop().equals(d.poll())) {
            return false;
        }
    }
  3. while (!s.isEmpty()) {
        if (!s.pop().equals(d.poll())) {
            return false;
        }
    }
  4. while (!s.isEmpty()) {
        if (!s.pop().equals(d.peek())) {
            return false;
        }
    }

2025 Aug 03

Question 9 MCQ · 7 marks

The merge(K key, V value, remappingFunction) function is defined as: If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.

Consider the Java code given below.

import java.util.*;
public class DepartmentScores {
    public static void main(String[] args) {
        Map<String, Integer> dept1 = new TreeMap<>();
        dept1.put("HR", 75);
        dept1.put("Finance", 80);
        dept1.put("Tech", 95);

        Map<String, Integer> dept2 = new TreeMap<>();
        dept2.put("Finance", 85);
        dept2.put("Tech", 90);
        dept2.put("HR", 78);
        dept2.put("Admin", 70);

        Map<String, Integer> combined = new TreeMap<>();
        for (Map.Entry<String, Integer> e : dept1.entrySet())
            combined.put(e.getKey(), e.getValue()); //LINE 1

        for (Map.Entry<String, Integer> e : dept2.entrySet())
            combined.merge(e.getKey(), e.getValue(),
                (oldVal, newVal) -> Math.max(oldVal, newVal));

        System.out.println(combined);
    }
}

Choose the correct option.

  1. LINE 1 generates a compilation error due to duplicate keys.

  2. The program generates the output: {Admin=70, Finance=85, HR=78, Tech=95}

  3. The program generates the output: {Finance=85, HR=75, Tech=95, Admin=70, Finance=85, HR=78, Tech=90}

  4. The program generates the output: {Admin=70, Finance=165, HR=153, Tech=185}

Question 3 MCQ · 6 marks

Consider the following Java code.

import java.util.*;
public class SetTest {
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(20);
        list.add(30);
        list.add(10);
        list.add(40);
        HashSet<Integer> set1 = new HashSet<Integer>(list);
        TreeSet<Integer> set2 = new TreeSet<Integer>(set1);
        set2.addAll(set1);
        System.out.println(set2);
    }
}

Choose the correct option.

  1. This program generates the output: [10, 20, 30, 40, 10, 20, 30, 40]

  2. This program generates the output: [10, 20, 30, 40]

  3. This program generates a set containing the elements 10, 20, 30, 40, but the order is unpredictable.

  4. This program generates the output: []

Question 13 MSQ · 7 marks

The following Java code maps books to the number of times they have been borrowed from a library and classifies them as popular books (borrowed more than 2 times) or less-read books.

import java.util.*;
public class Library {
    TreeSet<String> popularBooks = new TreeSet<>();
    TreeSet<String> lessReadBooks = new TreeSet<>();
    public boolean isPopular(int count) {
        return count > 2;
    }
    public void classifyBooks(HashMap<String, Integer> bookMap) {
        for (Map.Entry<String, Integer> entry : bookMap.entrySet()) {
            // LINE 1: if statement
            {
                popularBooks.add(entry.getKey());
            } else {
                lessReadBooks.add(entry.getKey());
            }
        }
    }
    public void displayBooks() {
        System.out.println("Popular Books: " + popularBooks);
        System.out.println("Less-read Books: " + lessReadBooks);
    }
    public static void main(String[] args) {
        HashMap<String, Integer> bookMap = new HashMap<>();
        bookMap.put("W", 4);
        bookMap.put("X", 1);
        bookMap.put("Y", 3);
        bookMap.put("Z", 2);

        Library lib = new Library();
        lib.classifyBooks(bookMap);
        lib.displayBooks();
    }
}

Choose the correct option to be filled in place of LINE 1 so that the output is:

Popular Books: [W, Y]
Less-read Books: [X, Z]
  1. if (isPopular(entry.getValue()))

  2. if (entry.getValue() > 2)

  3. if (entry.getKey().length() > 2)

  4. if (bookMap.containsKey(entry.getValue()))

Question 14 MSQ · 7 marks

Consider the Java code given below.

import java.util.*;
class Test {
    public static String findElement(Deque<String> dq, String element){
        while(!dq.isEmpty()) {
            // LINE 1
            {
                return "Element found";
            }
        }
        return "Element not found";
    }
    public static void main(String[] args) {
        Deque<String> dq = new ArrayDeque<String>();
        dq.push("apple");
        dq.push("banana");
        dq.push("cherry");
        dq.push("date");
        System.out.println(findElement(dq, "cherry"));
    }
}

Identify the appropriate option(s) to fill in place of LINE 1 such that the output is: Element found

  1. if(dq.peek() == element)

  2. if(dq.element() == element)

  3. if(dq.pop() == element)

  4. if(dq.remove() == element)

2022 July

Question 3 MCQ · 3 marks

Consider the Java code given below.

import java.util.*;
public class Test{
    public static void main(String[] args){
        var bill_march = new LinkedHashMap<String, Integer>();
        bill_march.put("suresh", 100);
        bill_march.put("mukesh", 150);
        bill_march.put("ganesh", 80);
        bill_march.put("pranay", 200);

        var bill_april = new LinkedHashMap<String, Integer>();
        bill_april.put("suresh", 200);
        bill_april.put("mukesh", 100);
        bill_april.put("ganesh", 100);
        bill_april.put("pranay", 100);

        var totalBill = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> e : bill_march.entrySet())
            totalBill.put(e.getKey(), e.getValue());
        for (Map.Entry<String, Integer> e : bill_april.entrySet())
            totalBill.merge(e.getKey(), e.getValue(), (x, y) -> y + x);
        System.out.println(totalBill);
    }
}

Choose the correct option.

  1. It generates runtime exception: NullPointerException

  2. It generates the output: {suresh=100, mukesh=150, ganesh=80, pranay=200}

  3. It generates the output: {suresh=200, mukesh=100, ganesh=100, pranay=100}

  4. It generates the output: {suresh=300, mukesh=250, ganesh=180, pranay=300}

Question 7 MCQ · 3 marks

Consider the Java code given below.

import java.util.*;
public class MapEx {
    TreeMap<String, String> map = new TreeMap<String, String>();
    public void addToMap(String key, String value) {
        map.put(key, _________________); //LINE-1
    }
    public static void main(String[] args) {
        MapEx obj = new MapEx();
        obj.addToMap("India", "Sachin");
        obj.addToMap("India", "Sehwag");
        obj.addToMap("Sri Lanka", "Hasaranga");
        obj.addToMap("Sri Lanka", "Asalanka");
        for (Map.Entry<String, String> entry : obj.map.entrySet()) {
            System.out.println(entry.getKey() + "-->" + entry.getValue());
        }
    }
}

Choose the correct option to fill in the blank in LINE-1 so that the output is:

India--> Sachin Sehwag
Sri Lanka--> Hasaranga Asalanka
  1. map.getDefault(key, "") + " " + value

  2. map.getOrDefault(key, "") + " " + value

  3. map.putOrDefault(key, "") + " " + value

  4. map.getOrDefault(key) + " " + value

Question 6 MCQ · 3 marks

Consider the Java code given below.

import java.util.*;
class Example{
    ArrayList<Integer> list1 = new ArrayList<Integer>();
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    public boolean property(int num){
        //return true if num is prime otherwise return false
    }
    public void iterateList(ArrayList<Integer> inputlist){
        Iterator<Integer> it = inputlist.iterator();
        while (it.hasNext()){
            int element = it.next();
            if (element % 2 == 0){
                list1.add(element);
            }
            else{
                if (property(element))
                    it.remove();
                else
                    list2.add(element);
            }
        }
        System.out.println(list1 + "\n" + list2);
    }
}
public class IteratorTest {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = 2; i < 15; i++)
            list.add(i);
        Example obj = new Example();
        obj.iterateList(list);
    }
}

What will the output be?

  1. [2, 4, 6, 8, 10, 12, 14]
    [9]
  2. [9]
    [2, 4, 6, 8, 10, 12, 14]
  3. [2, 4, 6, 8, 10, 12, 14]
    [3, 5, 7, 9, 11, 13]
  4. [3, 5, 7, 9, 11, 13]
    [2, 4, 6, 8, 10, 12, 14]

Question 12 MCQ · 4 marks

Consider the Java code given below.

import java.util.*;
public class Example {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Java");
        list.add("Programming language");
        list.add("IITM");
        list.add("Chennai");

        *****CODE BLOCK*****

        for (String str : list) {
            set1.add(str);
            set2.add(str);
        }
        for (String str : set1) {
            System.out.print(str + " ");
        }
        System.out.println();
        for (String str : set2) {
            System.out.print(str + " ");
        }
    }
}

Choose the correct option(s) to fill in CODE BLOCK so that the program always generates the following output:

Java Programming language IITM Chennai
Chennai IITM Java Programming language
  1. Set<String> set1 = new TreeSet<String>();
    Set<String> set2 = new LinkedHashSet<String>();
  2. Set<String> set1 = new LinkedHashSet<String>();
    Set<String> set2 = new TreeSet<String>();
  3. Set<String> set1 = new HashSet<String>();
    Set<String> set2 = new TreeSet<String>();
  4. Set<String> set1 = new LinkedHashSet<String>();
    Set<String> set2 = new HashSet<String>();

Check your answers →

Weeks covering this topic

Other Java topics