Skip to main content

Java Collections Framework – Interface, List, Queue, Sets, Maps

💁 The collection is a framework that is designed to store the objects and manipulate the design to store the objects.

Collections are used to perform the following operations:
  • Searching
  • Sorting
  • Manipulation
  • Insertion
  • Deletion
A group of objects is known as collections. All the classes and interfaces for collecting are available in Java utile package.

Given below are the Classes and Interfaces that are available in Collections:
Interfaces:
  • Collection
  • List
  • Set
  • Map
  • Sorted Set
  • Sorted Map
  • Queue
Classes:
  • Lists:
  • Array List
  • Vector
  • Linked List
Sets:
  • Hash set
  • Linked Hash Set
  • Tree Set
Maps:
  • HashMap
  • Hash Table
  • TreeMap
  • Linked Hashed Map
Queue:
  • Priority Queue

Ordered and Sorted in collections:- 
Ordered:
It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.
Sorted:
Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects.
lists available in the collection:-
Values added to the list is based on the index position and it is ordered by index position. Duplicates are allowed.
Types of Lists are:
Array List:
  • Fast iteration and fast Random Access.
  • It is an ordered collection (by index) and not sorted.
  • It implements Random Access Interface.
Example:
public class Fruits{
public static void main (String [ ] args){
ArrayList <String>names=new ArrayList <String>();
names.add (“apple”);
names.add (“cherry”);
names.add (“kiwi”);
names.add (“banana”);
names.add (“cherry”);
System.out.println (names);
}
}
Output:
[Apple, cherry, kiwi, banana, cherry]
From the output, Array List maintains the insertion order and it accepts the duplicates. But not sorted.
Vector:
It is same as Array List.
  • Vector methods are synchronized.
  • Thread safety.
  • It also implements the Random Access.
  • Thread safety usually causes a performance hit.
Example:
public class Fruit {
public static void main (String [ ] args){
Vector <String> names = new Vector <String> ( );
 names.add (“cherry”);
names.add (“apple”);
names.add (“banana”);
names.add (“kiwi”);
names.add (“apple”);
System.out.println (“names”);
}
}
Output:
[cherry,apple,banana,kiwi,apple]
Vector also maintains the insertion order and accepts the duplicates.
Linked List:
  • Elements are doubly linked to one another.
  • Performance is slow than Array list.
  • Good choice for insertion and deletion.
  • In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.
Example:
public class Fruit {
public static void main (String [ ] args){
Linkedlist <String> names = new linkedlist <String> ( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output
[ banana,cherry,apple,kiwi,banana]
Maintains the insertion order and accepts the duplicates.
Set available in a collection:-
Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.

Hash Set:

  • Unordered and unsorted.
  • Uses the hash code of the object to insert the values.
  • Use this when the requirement is “no duplicates and don’t care about the order”.
Example:
public class Fruit {
public static void main (String[ ] args){
HashSet<String> names = new HashSet <=String>( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output:
[banana, cherry, kiwi, apple]
Doesn’t follow any insertion order. Duplicates are not allowed.
Linked Hash set:
  • An ordered version of the hash set is known as Linked Hash Set.
  • Maintains a doubly-Linked list of all the elements.
  • Use this when the iteration order is required.
Example:
public class Fruit {
public static void main (String[ ] args){
LinkedHashSet<String> names = new LinkedHashSet <String>( ) ;
 names.add(“banana”);
 names.add(“cherry”);
 names.add(“apple”);
 names.add(“kiwi”);
 names.add(“banana”);
 System.out.println (names);
 }
}
Output:
[banana, cherry, apple, kiwi]
Maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.
Tree Set:
  • It is one of the two sorted collections.
  • Uses “Read-Black” tree structure and guarantees that the elements will be in ascending order.
  • We can construct a tree set with the constructor by using the comparable (or) comparator.
Example:
public class Fruits{
public static void main (String[ ]args) {
Treeset<String> names= new TreeSet<String>( ) ;
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[apple, banana, cherry, kiwi]
TreeSet sorts the elements in ascending order. And duplicates are not allowed.
Map available in a collection:-
Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses “equals ( )” method to determine whether two keys are same or different.
HashMap:
  • Unordered and unsorted map.
  • Hashmap is a good choice when we don’t care about the order.
  • It allows one null key and multiple null values.
Example:
Public class Fruit{
Public static void main(String[ ] args){
HashMap<Sting,String> names =new HashMap<String,String>( );
names.put(“key1”,“cherry”);
names.put (“key2”,“banana”);
names.put (“key3”,“apple”);
names.put (“key4”,“kiwi”);
names.put (“key1”,“cherry”);
System.out.println(names);
}
 }
Output:
{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}
Duplicate keys are not allowed in Map.
Doesn’t maintain any insertion order and is unsorted.
HashTable:
  • Like vector key, methods of the class are synchronized.
  • Thread safety and therefore slows the performance.
  • Doesn’t allow anything that is null.
Example:
public class Fruit{
public static void main(String[ ]args){
Hashtable<Sting,String> names =new Hashtable<String,String>( );
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}
 }
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}
Duplicate keys are not allowed.
 Linked HashMap:
  • Maintains insertion order.
  • Slower than Hashmap.
  • Can expect a faster iteration.
Example:
public class Fruit{
public static void main(String[ ] args){
LinkedHashMap<Sting,String> names =new LinkedHashMap<String,String>( );
 names.put(“key1”,“cherry”);
 names.put(“key2”,“apple”);
 names.put(“key3”,“banana”);
 names.put(“key4”,“kiwi”);
 names.put(“key2”,“orange”);
 System.out.println(names);
 }
 }
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}
Duplicate keys are not allowed.
TreeMap:
  • Sorted Map.
  • Like Tree set, we can construct a sort order with the constructor.
Example:
public class Fruit{
public static void main(String[ ]args){
TreeMap<Sting,String> names =new TreeMap<String,String>( );
names.put(“key1”,“cherry”);
names.put(“key2”,“banana”);
names.put(“key3”,“apple”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}
}
Output:
{key1=cherry, key2=banana, key3 =apple, key4=kiwi}
It is sorted in ascending order based on the key. Duplicate keys are not allowed.

Priority Queue:-
Linked list class has been enhanced to implement the queue interface. Queues can be handled with a linked list. Purpose of a queue is “Priority-in, Priority-out”.
Hence elements are ordered either naturally or according to the comparator. The elements ordering represents their relative priority.
Difference between HashMap and HashTable can be seen below:
HashMapHashTable
Methods are not synchronizedKey methods are synchronized
Not thread safetyThread safety
Iterator is used to iterate the valuesEnumerator is used to iterate the values
Allows one null key and multiple null valuesDoesn’t allow anything that is null
Performance is high than HashTablePerformance is slow
Difference between HashSet and TreeSet can be seen below:
HashSetTreeSet
Inserted elements are in random orderMaintains the elements in the sorted order
Can able to store null objectsCouldn’t store null objects
Performance is fastPerformance is slow

The Difference between Array and Array List can be understood from the below table:
                        Array                                         Array List    
Size should be given at the time of array declaration.

String[] name = new String[2]
Size may not be required. It changes the size dynamically.

ArrayList name = new ArrayList
To put an object into array we need to specify the index.

name[1] = “book”
No index required.

name.add(“book”)
Array is not type parameterizedArrayList in java 5.0 are parameterized.

Eg: This angle bracket is a type parameter which means a list of String.


Comments

Popular posts from this blog

Java Currency Formatter Solution

Given a  double-precision  number,  , denoting an amount of money, use the  NumberFormat  class'  getCurrencyInstance  method to convert   into the US, Indian, Chinese, and French currency formats. Then print the formatted values as follows: US: formattedPayment India: formattedPayment China: formattedPayment France: formattedPayment where   is   formatted according to the appropriate  Locale 's currency. Note:  India does not have a built-in Locale, so you must  construct one  where the language is  en  (i.e., English). Input Format A single double-precision number denoting  . Constraints Output Format On the first line, print  US: u  where   is   formatted for US currency.  On the second line, print  India: i  where   is   formatted for Indian currency.  On the third line...

Java Loops II print each element of our series as a single line of space-separated values.

We use the integers  ,  , and   to create the following series: You are given   queries in the form of  ,  , and  . For each query, print the series corresponding to the given  ,  , and   values as a single line of   space-separated integers. Input Format The first line contains an integer,  , denoting the number of queries.  Each line   of the   subsequent lines contains three space-separated integers describing the respective  ,  , and   values for that query. Constraints Output Format For each query, print the corresponding series on a new line. Each series must be printed in order as a single line of   space-separated integers. Sample Input 2 0 2 10 5 3 5 Sample Output 2 6 14 30 62 126 254 510 1022 2046 8 14 26 50 98 Explanation We have two queries: We use  ...

Java Static Initializer Block

Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks. It's time to test your knowledge of  Static initialization blocks . You can read about it  here. You are given a class  Solution  with a  main  method. Complete the given code so that it outputs the area of a parallelogram with breadth   and height  . You should read the variables from the standard input. If   or    , the output should be  "java.lang.Exception: Breadth and height must be positive"  without quotes. Input Format There are two lines of input. The first line contains  : the breadth of the parallelogram. The next line contains  : the height of the parallelogram. Constraints Output Format If both values are greater than zero, then the  main  method must output the area of the  parallelogram . Otherwise, pri...