Unit - 5
Collection Framework
Q1) Explain Collection Framework.
A1)
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
- It provides readymade architecture.
- It represents a set of classes and interfaces.
- It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:
- Interfaces and its implementations, i.e., classes
- Algorithm
Do You Know?
- What are the two ways to iterate the elements of a collection?
- What is the difference between ArrayList and LinkedList classes in collection framework?
- What is the difference between ArrayList and Vector classes in collection framework?
- What is the difference between HashSet and HashMap classes in collection framework?
- What is the difference between HashMap and Hashtable class?
- What is the difference between Iterator and Enumeration interface in collection framework?
- How can we sort the elements of an object? What is the difference between Comparable and Comparator interfaces?
- What does the hashcode() method?
- What is the difference between Java collection and Java collections?
Q2) Draw Hierarchy of Collection Framework
A2)
Let us see the hierarchy of Collection framework. The java.util package contains all the classes and interfaces for the Collection framework.
Q3) What are the methods of Collection interface?
A3)
There are many methods declared in the Collection interface. They are as follows:
No. | Method | Description |
1 | Public boolean add(E e) | It is used to insert an element in this collection. |
2 | Public boolean addAll(Collection<? extends E> c) | It is used to insert the specified collection elements in the invoking collection. |
3 | Public boolean remove(Object element) | It is used to delete an element from the collection. |
4 | Public boolean removeAll(Collection<?> c) | It is used to delete all the elements of the specified collection from the invoking collection. |
5 | Default boolean removeIf(Predicate<? super E> filter) | It is used to delete all the elements of the collection that satisfy the specified predicate. |
6 | Public boolean retainAll(Collection<?> c) | It is used to delete all the elements of invoking collection except the specified collection. |
7 | Public int size() | It returns the total number of elements in the collection. |
8 | Public void clear() | It removes the total number of elements from the collection. |
9 | Public boolean contains(Object element) | It is used to search an element. |
10 | Public boolean containsAll(Collection<?> c) | It is used to search the specified collection in the collection. |
11 | Public Iterator iterator() | It returns an iterator. |
12 | Public Object[] toArray() | It converts collection into array. |
13 | Public <T> T[] toArray(T[] a) | It converts collection into array. Here, the runtime type of the returned array is that of the specified array. |
14 | Public boolean isEmpty() | It checks if collection is empty. |
15 | Default Stream<E> parallelStream() | It returns a possibly parallel Stream with the collection as its source. |
16 | Default Stream<E> stream() | It returns a sequential Stream with the collection as its source. |
17 | Default Spliterator<E> spliterator() | It generates a Spliterator over the specified elements in the collection. |
18 | Public boolean equals(Object element) | It matches two collections. |
19 | Public int hashCode() | It returns the hash code number of the collection. |
Q4) Explain Iterator interface.
A4)
Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No. | Method | Description |
1 | Public boolean hasNext() | It returns true if the iterator has more elements otherwise it returns false. |
2 | Public Object next() | It returns the element and moves the cursor pointer to the next element. |
3 | Public void remove() | It removes the last elements returned by the iterator. It is less used. |
Q5) What is Iterable Interface?
A5)
The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface.
It contains only one abstract method. i.e.,
Iterator<T> iterator()
It returns the iterator over the elements of type T.
Q6) What is Collection Interface?
A6)
The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the methods that every collection will have. In other words, we can say that the Collection interface builds the foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection interface.
Q7) What is List Interface?
A7)
List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
- List <data-type> list1= new ArrayList();
- List <data-type> list2 = new LinkedList();
- List <data-type> list3 = new Vector();
- List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and access the elements from the list.
Q8) Explain list interface classes.
A8)
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the following example.
- Import java.util.*;
- Class TestJavaCollection1{
- Public static void main(String args[]){
- ArrayList<String> list=new ArrayList<String>();//Creating arraylist
- List.add("Ravi");//Adding object in arraylist
- List.add("Vijay");
- List.add("Ravi");
- List.add("Ajay");
- //Traversing list through Iterator
- Iterator itr=list.iterator();
- While(itr.hasNext()){
- System.out.println(itr.next());
- }
- }
- }
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.
Consider the following example.
- Import java.util.*;
- Public class TestJavaCollection2{
- Public static void main(String args[]){
- LinkedList<String> al=new LinkedList<String>();
- Al.add("Ravi");
- Al.add("Vijay");
- Al.add("Ravi");
- Al.add("Ajay");
- Iterator<String> itr=al.iterator();
- While(itr.hasNext()){
- System.out.println(itr.next());
- }
- }
- }
Output:
Ravi
Vijay
Ravi
Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
- Import java.util.*;
- Public class TestJavaCollection3{
- Public static void main(String args[]){
- Vector<String> v=new Vector<String>();
- v.add("Ayush");
- v.add("Amit");
- v.add("Ashish");
- v.add("Garima");
- Iterator<String> itr=v.iterator();
- While(itr.hasNext()){
- System.out.println(itr.next());
- }
- }
- }
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
Consider the following example.
- Import java.util.*;
- Public class TestJavaCollection4{
- Public static void main(String args[]){
- Stack<String> stack = new Stack<String>();
- Stack.push("Ayush");
- Stack.push("Garvit");
- Stack.push("Amit");
- Stack.push("Ashish");
- Stack.push("Garima");
- Stack.pop();
- Iterator<String> itr=stack.iterator();
- While(itr.hasNext()){
- System.out.println(itr.next());
- }
- }
- }
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:
- Queue<String> q1 = new PriorityQueue();
- Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given below.
Priority Queue
The Priority Queue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. Priority Queue doesn't allow null values to be stored in the queue.
Consider the following example.
- Import java.util.*;
- Public class TestJavaCollection5{
- Public static void main(String args[]){
- PriorityQueue<String> queue=new PriorityQueue<String>();
- Queue.add("Amit Sharma");
- Queue.add("Vijay Raj");
- Queue.add("JaiShankar");
- Queue.add("Raj");
- System.out.println("head:"+queue.element());
- System.out.println("head:"+queue.peek());
- System.out.println("iterating the queue elements:");
- Iterator itr=queue.iterator();
- While(itr.hasNext()){
- System.out.println(itr.next());
- }
- Queue.remove();
- Queue.poll();
- System.out.println("after removing two elements:");
- Iterator<String> itr2=queue.iterator();
- While(itr2.hasNext()){
- System.out.println(itr2.next());
- }
- }
- }
Output:
Head:Amit Sharma
Head:Amit Sharma
Iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
After removing two elements:
Raj
Vijay Raj
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.
Deque can be instantiated as:
Deque d = new ArrayDeque();
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.
- Import java.util.*;
- Public class TestJavaCollection6{
- Public static void main(String[] args) {
- //Creating Deque and adding elements
- Deque<String> deque = new ArrayDeque<String>();
- Deque.add("Gautam");
- Deque.add("Karan");
- Deque.add("Ajay");
- //Traversing elements
- For (String str : deque) {
- System.out.println(str);
- }
- }
- }
Output:
Gautam
Karan
Ajay
Q9) Explain List interface and its classes.
A9)
List in Java provides the facility to maintain the ordered collection.
It contains the index-based methods to insert, update, delete and search the elements.
It can have the duplicate elements also. We can also store the null elements in the list.
The implementation classes of List interface are Array List, Linked List, Stack and Vector.
Declaration:
Public interface List<E> extends Collection<E>
Java List Methods:
Method | Description | |
Void add(int index, E element) | It is used to insert the specified element at the specified position in a list. | |
Boolean add(E e) | It is used to append the specified element at the end of a list. | |
Boolean addAll(Collection<? extends E> c) | It is used to append all of the elements in the specified collection to the end of a list. | |
Boolean addAll(int index, Collection<? extends E> c) | It is used to append all the elements in the specified collection, starting at the specified position of the list. | |
Void clear() | It is used to remove all of the elements from this list. | |
Boolean equals(Object o) | It is used to compare the specified object with the elements of a list. | |
Int hashcode() | It is used to return the hash code value for a list. | |
E get(int index) | It is used to fetch the element from the particular position of the list. | |
Boolean isEmpty() | It returns true if the list is empty, otherwise false. | |
Int lastIndexOf(Object o) | It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. | |
Object[] toArray() | It is used to return an array containing all of the elements in this list in the correct order. | |
<T> T[] toArray(T[] a) | It is used to return an array containing all of the elements in this list in the correct order. | |
Boolean contains(Object o) | It returns true if the list contains the specified element | |
Boolean containsAll(Collection<?> c) | It returns true if the list contains all the specified element | |
Int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. | |
E remove(int index) | It is used to remove the element present at the specified position in the list. |
|
Boolean remove(Object o) | It is used to remove the first occurrence of the specified element. |
|
Boolean removeAll(Collection<?> c) | It is used to remove all the elements from the list. |
|
Void replaceAll(UnaryOperator<E> operator) | It is used to replace all the elements from the list with the specified element. |
|
Void retainAll(Collection<?> c) | It is used to retain all the elements in the list that are present in the specified collection. |
|
E set(int index, E element) | It is used to replace the specified element in the list, present at the specified position. |
|
Void sort(Comparator<? super E> c) | It is used to sort the elements of the list on the basis of specified comparator. |
|
Spliterator<E> spliterator() | It is used to create spliterator over the elements in a list. |
|
List<E> subList(int fromIndex, int toIndex) | It is used to fetch all the elements lies within the given range. |
|
Int size() | It is used to return the number of elements present in the list. |
|
Example:
- Creating a List of type String using ArrayList
List<String> list=new ArrayList<String>();
2. Creating a List of type Integer using ArrayList
List<Integer> list=new ArrayList<Integer>();
3. Creating a List of type Book using ArrayList
List<Book> list=new ArrayList<Book>();
4. Creating a List of type String using LinkedList
List<String> list=new LinkedList<String>();
List Example
Let's see a simple example of List where we are using the Array List class as the implementation.
Import java.util.*;
Public class ListExample1{
Public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
List.add("Mango");
List.add("Apple");
List.add("Banana");
List.add("Grapes");
//Iterating the List element using for-each loop
For(String fruit:list)
System.out.println(fruit);
}
}
Output:
Mango
Apple
Banana
Grapes
How to convert Array to List
We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method. Let's see a simple example to convert array elements into List.
Import java.util.*;
Public class ArrayToListExample{
Public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
//Converting Array to List
List<String> list=new ArrayList<String>();
For(String lang:array){
List.add(lang);
}
System.out.println("Printing List: "+list);
}
}
Output:
Printing Array: [Java, Python, PHP, C++]
Printing List: [Java, Python, PHP, C++]
How to convert List to Array
We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements into array.
Import java.util.*;
Public class ListToArrayExample{
Public static void main(String args[]){
List<String> fruitList = new ArrayList<>();
FruitList.add("Mango");
FruitList.add("Banana");
FruitList.add("Apple");
FruitList.add("Strawberry");
//Converting ArrayList to Array
String[] array = fruitList.toArray(new String[fruitList.size()]);
System.out.println("Printing Array: "+Arrays.toString(array));
System.out.println("Printing List: "+fruitList);
}
}
Output:
Printing Array: [Mango, Banana, Apple, Strawberry]
Printing List: [Mango, Banana, Apple, Strawberry]
Q10) What is the difference between List, Set, and Map interface?
A10)
Difference between List, Set, and Map interface:
The List, Set and Map interfaces are significant members of the Java
- Ordering: -
- List: - represents an ordered sequence in Java whose elements are accessible by index.
- Set: - represents a distinct collection of elements in Java which can be either ordered or unordered, depending on the implementation.
Example: a) HashSet implementation is unordered
b) TreeSet implementation is ordered by natural order or provided comparator.
3. Map: - represents the mapping of the key to values in Java. The ordering in Map is also implementation-specific
Example: Tree Map class is ordered while the HashMap class is not.
B. Duplicates:
- List: List can have duplicate elements
- Set: A set contain only distinct elements
- Map: Map doesn’t permit duplicate keys, i.e., each key can map to at most one value.
C. Null Values:
- List: It allows any number of null values
- Set: a set contains at most one null element.
- Map: Map typically allows null as a key and value, but some implementations prohibit null keys and values.
D. Implementing Classes:
- List: The most popular implementing classes of the List interface are Array List and LinkedList
- Set: set interfaces included HashSet, TreeSet, Linked Hash Set
- Map: Map interfaces offers Tree Map, Linked Hash Map, Tree Map
E. When to use List, Map and Set:
- List: List can be used when the insertion order of an elements need to be maintained.
- Set: We can use set if we need to maintain a collection that contain no duplicates.
- Map: when data is key-value pairs and need fast retrieval of value based on some key.
Getter And Setter classes in java
Getter method:
- A method which is used to retrieve/get the value of a variable or return the value of the private member variable is called getter method in Java.
- This method is also known as accessor method. For every private variable, we should create a getter method.
- Depending on the access level giving to the variable, we can set the access modifier of its getter method.
- If we declare instance variables as private, we will have to add public getter methods for each one.
- The signature of a getter method in Java is as follows:
Public returnType getPropertyName()
- If the returnType is boolean, the getter method should defined
Public boolean isPropertyName()
Q11) Explain Set interface and its classes.
A11)
Set Interface in Java is present in java.util package.
It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, Linked Hash Set, and TreeSet.
Set can be instantiated as:
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Consider the following example.
Import java.util.*;
Public class TestJavaCollection7{
Public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
Set.add("Ravi");
Set.add("Vijay");
Set.add("Ravi");
Set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
While(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay
Linked Hash Set
Linked Hash Set class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.
Consider the following example
Import java.util.*;
Public class TestJavaCollection8{
Public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
Set.add("Ravi");
Set.add("Vijay");
Set.add("Ravi");
Set.add("Ajay");
Iterator<String> itr=set.iterator();
While(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
Consider the following example:
Import java.util.*;
Public class TestJavaCollection9{
Public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
Set.add("Ravi");
Set.add("Vijay");
Set.add("Ravi");
Set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
While(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
Q12) Explain Map interface and its classes.
A12)
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
Java Map Hierarchy
There are two interfaces for implementing Map in java: Map and Sorted Map, and three classes: HashMap, Linked Hash Map, and Tree Map. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and Linked Hash Map allow null keys and values, but Tree Map doesn't allow any null key or value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
Class | Description |
HashMap | HashMap is the implementation of Map, but it doesn't maintain any order. |
LinkedHashMap | LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order. |
TreeMap | TreeMap is the implementation of Map and SortedMap. It maintains ascending order. |
Useful methods of Map interface
Method | Description |
V put(Object key, Object value) | It is used to insert an entry in the map. |
Void putAll(Map map) | It is used to insert the specified map in the map. |
V putIfAbsent(K key, V value) | It inserts the specified value with the specified key in the map only if it is not already specified. |
V remove(Object key) | It is used to delete an entry for the specified key. |
Boolean remove(Object key, Object value) | It removes the specified values with the associated specified keys from the map. |
Set keySet() | It returns the Set view containing all the keys. |
Set<Map.Entry<K,V>> entrySet() | It returns the Set view containing all the keys and values. |
Void clear() | It is used to reset the map. |
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) | It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. |
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) | It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. |
Boolean containsValue(Object value) | This method returns true if some value equal to the value exists within the map, else return false. |
Boolean containsKey(Object key) | This method returns true if some key equal to the key exists within the map, else return false. |
Boolean equals(Object o) | It is used to compare the specified Object with the Map. |
Void forEach(BiConsumer<? super K,? super V> action) | It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
V get(Object key) | This method returns the object that contains the value associated with the key. |
V getOrDefault(Object key, V defaultValue) | It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. |
Int hashCode() | It returns the hash code value for the Map |
Boolean isEmpty() | This method returns true if the map is empty; returns false if it contains at least one key. |
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) | If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
Map Example
Import java.util.*;
Class MapExample2{
Public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
Map.put(100,"Amit");
Map.put(101,"Vijay");
Map.put(102,"Rahul");
//Elements can traverse in any order
For(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
102 Rahul
100 Amit
101 Vijay
Map Example: comparingByKey()
Import java.util.*;
Class MapExample3{
Public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
Map.put(100,"Amit");
Map.put(101,"Vijay");
Map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
Map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey())
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}
Output:
100=Amit
101=Vijay
102=Rahul
Map Example: comparingByKey() in Descending Order
Import java.util.*;
Class MapExample4{
Public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>(); map.put(100,"Amit");
Map.put(101,"Vijay");
Map.put(102,"Rahul");
//Returns a Set view of the mappings contained in this map
Map.entrySet()
//Returns a sequential Stream with this collection as its source
.stream()
//Sorted according to the provided Comparator
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
//Performs an action for each element of this stream
.forEach(System.out::println);
}
}
Output:
102=Rahul
101=Vijay
100=Amit
Q13) Explain Queue Interface.
A13)
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:
3. Queue<String> q1 = new PriorityQueue();
4. Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given below.
Priority Queue
The Priority Queue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. Priority Queue doesn't allow null values to be stored in the queue.
Consider the following example.
25. import java.util.*;
26. public class TestJavaCollection5{
27. public static void main(String args[]){
28. PriorityQueue<String> queue=new PriorityQueue<String>();
29. queue.add("Amit Sharma");
30. queue.add("Vijay Raj");
31. queue.add("JaiShankar");
32. queue.add("Raj");
33. System.out.println("head:"+queue.element());
34. System.out.println("head:"+queue.peek());
35. System.out.println("iterating the queue elements:");
36. Iterator itr=queue.iterator();
37. while(itr.hasNext()){
38. System.out.println(itr.next());
39. }
40. queue.remove();
41. queue.poll();
42. System.out.println("after removing two elements:");
43. Iterator<String> itr2=queue.iterator();
44. while(itr2.hasNext()){
45. System.out.println(itr2.next());
46. }
47. }
48. }
Output:
Head:Amit Sharma
Head:Amit Sharma
Iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
After removing two elements:
Raj
Vijay Raj
Q14) How to convert Array to List?
A14)
We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method. Let's see a simple example to convert array elements into List.
Import java.util.*;
Public class ArrayToListExample{
Public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
//Converting Array to List
List<String> list=new ArrayList<String>();
For(String lang:array){
List.add(lang);
}
System.out.println("Printing List: "+list);
}
}
Output:
Printing Array: [Java, Python, PHP, C++]
Printing List: [Java, Python, PHP, C++]
Q15) How to convert List to Array?
A15)
We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements into array.
Import java.util.*;
Public class ListToArrayExample{
Public static void main(String args[]){
List<String> fruitList = new ArrayList<>();
FruitList.add("Mango");
FruitList.add("Banana");
FruitList.add("Apple");
FruitList.add("Strawberry");
//Converting ArrayList to Array
String[] array = fruitList.toArray(new String[fruitList.size()]);
System.out.println("Printing Array: "+Arrays.toString(array));
System.out.println("Printing List: "+fruitList);
}
}
Output:
Printing Array: [Mango, Banana, Apple, Strawberry]
Printing List: [Mango, Banana, Apple, Strawberry]