Collections
in java is a framework that provides an architecture to store and manipulate
the group of objects.
All
the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by Java Collections.
Collections
are like containers that groups multiple items in a single unit
Types of Collections
1. Sorted
2. Unsorted
3. Ordered
4. Unordered
Core Interfaces
Collection
- A collection represents a group of objects known
as its elements. Collection is the parent interface of
collection APISet
— a collection that cannot contain duplicate
elements. This interface models the mathematical set.List
— an ordered collection (sometimes called a sequence). List
s can contain duplicate elements.Queue
— a collection which order elements in a FIFO
(first-in, first-out) manner. Although priority queues, order elements according to a
supplied comparator or the elements' natural ordering.Deque
— a collection used to hold multiple elements
prior to processing. Besides basic Collection
operations, a Deque
provides additional insertion, extraction, and
inspection operations. Deques can be used both as FIFO (first-in, first-out)
and LIFO (last-in, first-out). In a deque all new elements can be inserted,
retrieved and removed at both ends. Map
— it contains key-value pair. A Map
cannot contain duplicate keys; each key can map
to at most one value.SortedSet
— a Set
that maintains its elements in ascending order.
Sorted sets are used for naturally ordered sets.SortedMap
— a Map
that maintains its mappings in ascending key
order. This is the Map
analog of SortedSet
. Sorted maps are used for naturally ordered
collections of key/value pairs, such as dictionaries and telephone directories.
Note:
None of the Map related classes & Interface extend from Collection.
List Implementation
ArrayList – java.util.ArrayList class is most widely
used collection. It grows dynamically and provide powerful insertion a search
mechanism.
Code snippet –
List<String>
list = new ArrayList<>();
list.add("string values");
Note:
Collection holds object but not primitivetype, primitive values will be handled
via Autoboxing
Sorting Collections –
Comparable interface – comparable interface is used by sort() method
to sort to list and arrays of object. Comparable interface has a single method
compareTo()
Invocation of compareTo() is
– (Int x = thisObject.compareTo(anotherObject))
If x is negative than thisObject < anotherObject
If x is zero than thisObject = anotherObject
If x is positive than thisObject >
anotherObject
Code snippet –
Collections.sort(list);
Arrays.sort(array);
Comparator interface – comparator interface gives the capability to
sort the given collection any numbers of different way. In other hand we can
use it to sort instance of any class.
Comparator interface also
have single method compare().
Code snippet-
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Here we have created a PersonComparator
class for the sorting
* of Person on the basis of the name.
* @author Manoj
*/
public class ComparatorTest {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("P1"));
personList.add(new Person("P3"));
personList.add(new Person("P2"));
Collections.sort(personList, new PersonComparator());
personList.forEach(person -> System.out.println(person.getName()));
}
}
class PersonComparator implements Comparator<Person> {
public int compare(Person personOne, Person personTwo) {
return personOne.getName().compareTo(personTwo.getName());
}
}
class Person {
private String name;
Person(String name){
this.name = name;
}
public String getName() {
return name;
}
}
Set Implementation
HashSet
– is an unordered and unsorted collection which
contains unique values.
Code Snippet-
Set<String> set = new HashSet<>();
set.add("H1");
Here set.add() method return boolean value if we
insert duplicate value it will return false.
LinkedHasSet
- LinkedHashSet class is a Hash table and Linked list
implementation. It contains unique elements and maintains insertion order it
also permit null values.
Code Snippet –
Set<String>
set = new LinkedHashSet<>();
set.add("H1");
set.add(null);
TreeSet
- TreeSet is implemented using a tree structure(red-black
tree in algorithm book). The elements in a set are sorted, but
the add, remove, and contains methods has time complexity
of O(log (n)). It offers several methods to deal with the ordered set like
first(), last(), headSet(), tailSet(), etc.
Code Snippet-
import java.io.IOException;
import java.util.TreeSet;
/**
* @author Manoj
*/
public class Test {
public static void main(String[] args) throws IOException {
TreeSet<Integer> tree = new TreeSet<Integer>();
tree.add(1);
tree.add(3);
tree.add(2);
tree.forEach(val ->
System.out.println(val));
}
}
Map Implementation
HashMap
– HashMap stores the data in key value pairs. We can
put one null key and multiple null values in HashMap. HashMap does not call
hashcode when we put null key and null Key is handled as special case. HashMap
puts null key in bucket 0 and put null value for this null key.
It does it by linked list data structure it uses
internally.
Code Snippet –
import java.util.HashMap;
import java.util.Map;
/**
* @author Manoj
*/
public class Test {
public static void main(String[] args) throws IOException {
Map<String,String> map = new HashMap<>();
map.put(null, null);
System.out.println(map.get(null));
}
}
When we search for null key in HashMap it searches
in bucket 0.
LinkedHashMap
- LinkedHashMap is
a Hash table and linked list implementation of the Map interface. LinkedHashMap
maintain insertion order.
Code Snippet –
import java.util.LinkedHashMap;
/**
* LinkedHashMapTest contains LinkedHashMap
sample code which
* maintain insertion order
* @author mku117
*/
public class LinkedHashMapTest {
public static void main(String args[]) {
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>();
lhmap.put(2, "M1");
lhmap.put(3, "M2");
lhmap.put(1, "M3");
lhmap.forEach((key,value) -> System.out.println("key: "+key+"
value:"+value));
}
}
TreeMap
- TreeMap class implements the Map interface by using a tree. A TreeMap
contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class. It conatins unique values, it can’t allow null key
but have multiple null values.
If we put null as key than it will through
java.lang.NullPointerException
Code Snippet –
import java.util.Map;
import java.util.TreeMap;
/**
* TreeMap example.
* @author Manoj
*/
public class Test {
public static void main(String[] args) throws IOException {
Map<String,String> map = new TreeMap<>();
map.put("1", null);
System.out.println(map.get(null));
}
}
Legacy Classes and Interface
All the legacy classes are synchronized. Different
legacy interface and classes are as follows-
Enumeration
Interface - enumerate the element in a collection of object.
Vector
– it implements a dynamic array but it’s synchronized.
Stack –
it is a subclass of Vector that implement standard
stack (LIFO) features
Dictionary
– It is an abstract class that represents key/value
storage.
HashTable
– it’s part of original java.util and is concrete
implementation of Dictionary but now it’s integrated with Collections
Framework. It’s store key/value pair
doesn’t allow null key or null value. HashTable is synchronized.
Properties
– It’s a subclass of HashTable, it is used to maintain
lists of values in which the key and value both are string.
Nice information, very usefull thanks
ReplyDelete