Java Questions Part8 - Programs on Collections

1.Write a program To find duplicates between two lists?

Answer:
public class ArrayListExample

{
   public static void main(String[] args)

    {
        ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "f"));

        ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));

        listOne.retainAll(listTwo);

        System.out.println(listOne);

    }

}

Output:
[a, b, c, d]

2. Write a program to compare two Hashmap for equality?

Answer: Important points about Java Hashmap class are:
  • Java HashMap class contains values based on the key.
  • Java HashMap class contains only unique keys.
  • Java HashMap class may have one null key and multiple null values.
  • Java HashMap class is non synchronized.
  • Java HashMap class maintains no order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
public class HashMapExample

{
    public static void main(String[] args) throws CloneNotSupportedException

    {
        HashMap<Integer, String> map1 = new HashMap<>();

        map1.put(1, "A");

        map1.put(2, "B");

        map1.put(3, "C");

        //Same as map1

        HashMap<Integer, String> map2 = new HashMap<>();

        map2.put(3, "C");

        map2.put(1, "A");

        map2.put(2, "B");

        //Different from map1

        HashMap<Integer, String> map3 = new HashMap<>();

        map3.put(1, "A");

        map3.put(2, "B");

        map3.put(3, "C");

        map3.put(3, "D");

        System.out.println(map1.equals(map2));  //true

        System.out.println(map1.equals(map3));  //false

    }

}

Output:
true

false

3. Write a Java program to demonstrate ArrayList?

Answer: Important points about Java ArrayList class are:
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.
import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

 public class CreateArrayListExample {

                public static void main(String[] args) {

                                // Creating an ArrayList of String

                                List<String> animals = new ArrayList<>();

                                // Adding new elements to the ArrayList

                                animals.add("Lion");

                                animals.add("Tiger");

                                animals.add("Cat");

                                animals.add("Dog");

                                System.out.println(animals);

                                // Traversing list through Iterator

                                Iterator itr = animals.iterator();

                                while (itr.hasNext()) {

                                                System.out.println(itr.next());

                                }

                                // Adding an element at a particular index in an ArrayList

                                animals.add(2, "Elephant");

                                System.out.println(animals);

                }

}

Output:
[Lion, Tiger, Cat, Dog]

Lion

Tiger

Cat

Dog

[Lion, Tiger, Elephant, Cat, Dog]

4. Write a Java program to demonstrate LinkedList?

Answer:  important points about Java LinkedList are:
  • Java LinkedList class can contain duplicate elements.
  • Java LinkedList class maintains insertion order.
  • Java LinkedList class is non synchronized.
  • In Java LinkedList class, manipulation is fast because no shifting needs to occur.
  • Java LinkedList class can be used as a list, stack or queue.
import java.util.*; 

public class LinkedListExample{ 

 public static void main(String args[]){ 

 LinkedList<String> ll=new LinkedList<String>(); 

           System.out.println("Initial list of elements: "+ll); 

           ll.add("Ravi"); 

           ll.add("Vijay"); 

           ll.add("Ajay"); 

           System.out.println("After invoking add(E e) method: "+ll); 

           //Adding an element at the specific position 

           ll.add(1, "Gaurav"); 

           System.out.println("After invoking add(int index, E element) method: "+ll); 

           LinkedList<String> ll2=new LinkedList<String>(); 

           ll2.add("Sonoo"); 

           ll2.add("Hanumat"); 

           //Adding second list elements to the first list 

           ll.addAll(ll2); 

           System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ll); 

           LinkedList<String> ll3=new LinkedList<String>(); 

           ll3.add("John"); 

           ll3.add("Rahul"); 

           //Adding second list elements to the first list at specific position 

           ll.addAll(1, ll3); 

           System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ll); 

           //Adding an element at the first position 

           ll.addFirst("Lokesh"); 

           System.out.println("After invoking addFirst(E e) method: "+ll); 

           //Adding an element at the last position 

           ll.addLast("Harsh"); 

           System.out.println("After invoking addLast(E e) method: "+ll); 

 } 

} 

Output:
Initial list of elements: []

After invoking add(E e) method: [Ravi, Vijay, Ajay]

After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]

After invoking addAll(Collection<? extends E> c) method:

[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

After invoking addAll(int index, Collection<? extends E> c) method:

[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

After invoking addFirst(E e) method:

[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

After invoking addLast(E e) method:

[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

5. Write a Java program to demonstrate Hashset?

Answer: The important points about Java HashSet class are:
  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.
  • HashSet allows null value.
  • HashSet class is non synchronized.
  • HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
  • HashSet is the best approach for search operations.
  • The initial default capacity of HashSet is 16, and the load factor is 0.75.
public class HashSetExample {

    public static void main(String[] args) {

        // Creating a HashSet

        Set<String> daysOfWeek = new HashSet<>();

        // Adding new elements to the HashSet

        daysOfWeek.add("Monday");

        daysOfWeek.add("Tuesday");

        daysOfWeek.add("Wednesday");

        daysOfWeek.add("Thursday");

        daysOfWeek.add("Friday");

        daysOfWeek.add("Saturday");

        daysOfWeek.add("Sunday");

        // Adding duplicate elements will be ignored

        daysOfWeek.add("Monday");

        System.out.println(daysOfWeek);

    }

}

Output:
[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]

6. Write a Java program to demonstrate LinkedHashSet?

Answer: The important points about Java LinkedHashSet class are:
  • Java LinkedHashSet class contains unique elements only like HashSet.
  • Java LinkedHashSet class provides all optional set operation and permits null elements.
  • Java LinkedHashSet class is non synchronized.
  • Java LinkedHashSet class maintains insertion order.
public class LinkedHashDemo 

{  
    public static void main(String[] args) 

    {  
        LinkedHashSet<String> linkedset = 

                           new LinkedHashSet<String>();  

        // Adding element to LinkedHashSet  

        linkedset.add("A");  

        linkedset.add("B");  

        linkedset.add("C");  

        linkedset.add("D"); 

        // This will not add new element as A already exists 

        linkedset.add("A"); 

        linkedset.add("E");  

        System.out.println("Size of LinkedHashSet = " +

                                    linkedset.size());  

        System.out.println("Original LinkedHashSet:" + linkedset);  

        System.out.println("Removing D from LinkedHashSet: " +

                            linkedset.remove("D"));  

        System.out.println("Trying to Remove Z which is not "+

                            "present: " + linkedset.remove("Z"));  

        System.out.println("Checking if A is present=" + 

                            linkedset.contains("A"));

        System.out.println("Updated LinkedHashSet: " + linkedset);  

    }  

}  

Output:
Size of LinkedHashSet=5

Original LinkedHashSet:[A, B, C, D, E]

Removing D from LinkedHashSet: true

Trying to Remove Z which is not present: false

Checking if A is present=true

Updated LinkedHashSet: [A, B, C, E]

7. Write a Java program to demonstrate TreeSet?

Answer: The important points about Java TreeSet class are:
  • Java TreeSet class contains unique elements only like HashSet.
  • Java TreeSet class access and retrieval times are quiet fast.
  • Java TreeSet class doesn't allow null element.
  • Java TreeSet class is non synchronized.
  • Java TreeSet class maintains ascending order.
public class TreeSetExample {

    public static void main(String[] args) {

        // Creating a TreeSet

        SortedSet<String> fruits = new TreeSet<>();

        // Adding new elements to a TreeSet

        fruits.add("Banana");

        fruits.add("Apple");

        fruits.add("Pineapple");

        fruits.add("Orange");

        System.out.println("Fruits Set : " + fruits);

        // Duplicate elements are ignored

        fruits.add("Apple");

        System.out.println("After adding duplicate element \"Apple\" : " + fruits);

        // This will be allowed because it's in lowercase.

        fruits.add("banana");

        System.out.println("After adding \"banana\" : " + fruits);

    }

}


Output:
Fruits Set : [Apple, Banana, Orange, Pineapple]

After adding duplicate element "Apple" : [Apple, Banana, Orange, Pineapple]

After adding "banana" : [Apple, Banana, Orange, Pineapple, banana]

8. Write a Java program to demonstrate PriorityQueue?

Answer:  PriorityQueue doesn’t permit null.
  • We can’t create PriorityQueue of Objects that are non-comparable
  • PriorityQueue are unbound queues.
  • The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements — ties are broken arbitrarily.
  • The queue retrieval operations poll,  remove,  peek, and element access the element at the head of the queue.
  • It inherits methods from AbstractQueue, AbstractCollection, Collection and Object class.
class PriorityQueueTest{

    public static void main(String args[])

    {
        // Creating empty priority queue

        PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

        // Adding items to the pQueue using add()

        pQueue.add(10);

        pQueue.add(20);

        pQueue.add(15);

        // Printing the top element of PriorityQueue

        System.out.println(pQueue.peek());

        // Printing the top element and removing it

        // from the PriorityQueue container

        System.out.println(pQueue.poll());

        // Printing the top element again

        System.out.println(pQueue.peek());

    }

}

Output:
10

10

15

9. Write a Java program to demonstrate LinkedHashMap ?
Answer: Java LinkedHashMap contains values based on the key.
  • Java LinkedHashMap contains unique elements.
  • Java LinkedHashMap may have one null key and multiple null values.
  • Java LinkedHashMap is non synchronized.
  • Java LinkedHashMap maintains insertion order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
class LinkedHashMapDemo{ 

 public static void main(String args[]){ 

   LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();          

      map.put(100,"Amit");   

     map.put(101,"Vijay");   

     map.put(102,"Rahul");   

       //Fetching key 

       System.out.println("Keys: "+map.keySet()); 

       //Fetching value 

       System.out.println("Values: "+map.values()); 

       //Fetching key-value pair 

       System.out.println("Key-Value pairs: "+map.entrySet()); 

 } 

} 

Output:
Keys: [100, 101, 102]

Values: [Amit, Vijay, Rahul]



Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]

10. Write a Java program to demonstrate TreeMap?

Answer: Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • Java TreeMap contains only unique elements.
  • Java TreeMap cannot have a null key but can have multiple null values.
  • Java TreeMap is non synchronized.
  • Java TreeMap maintains ascending order.
public class TreeMapExample {

    public static void main(String[] args) {

        // Creating a TreeMap

        SortedMap<String, String> fileExtensions  = new TreeMap<>();

        // Adding new key-value pairs to a TreeMap

        fileExtensions.put("python", ".py");

        fileExtensions.put("c++", ".cpp");

        fileExtensions.put("kotlin", ".kt");

        fileExtensions.put("golang", ".go");

        fileExtensions.put("java", ".java");

        // Printing the TreeMap (Output will be sorted based on keys)

        System.out.println(fileExtensions);

    }
}

Output:
{c++=.cpp, golang=.go, java=.java, kotlin=.kt, python=.py}

11. Write a Java program to demonstrate Hashtable?

Answer: A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
  • Java Hashtable class contains unique elements.
  • Java Hashtable class doesn't allow null key or value.
  • Java Hashtable class is synchronized.
  • The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
public class HashtableExample {

 public static void main(String[] args) {

   Enumeration names;

   String key;

   // Creating a Hashtable

   Hashtable<String, String> hashtable =

              new Hashtable<String, String>();

   // Adding Key and Value pairs to Hashtable

   hashtable.put("Key1","Chaitanya");

   hashtable.put("Key2","Ajeet");

   hashtable.put("Key3","Peter");

   hashtable.put("Key4","Ricky");

   hashtable.put("Key5","Mona");

   names = hashtable.keys();

   while(names.hasMoreElements()) {

      key = (String) names.nextElement();

      System.out.println("Key: " +key+ " & Value: " +

      hashtable.get(key));

   }

 }

}

Output:

Key: Key4 & Value: Ricky

Key: Key3 & Value: Peter

Key: Key2 & Value: Ajeet

Key: Key1 & Value: Chaitanya

Key: Key5 & Value: Mona

No comments:

Post a Comment