List, Map, Tree and Binary Search Tree
List, Map, Tree and Binary Search Tree
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
} }}
Example of List: Book List
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ListExample5 {
public static void main(String[] args) {
List
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Map
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.
Map
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but
TreeMap 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.
Map
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but
TreeMap 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.
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.
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.
Map
Map.Entry Interface
Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It returns a collection-view of the map, whose
elements are of this class. It provides methods to get key and value.
Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value
corresponding to this entry with the
specified value.
boolean equals(Object o) It is used to compare the specified object
with the other existing objects.
Map
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());
}
}
}
102 Rahul
100 Amit
101 Vijay
Map
Java 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);
}
}
.sorted(Map.Entry.comparingByValue()) // Camparing by value
Java TreeSet class
A tree is also one of the data structures that represent hierarchical data.
A tree data structure is a non-linear data structure because it does not store in a sequential manner. It is a hierarchical
structure as elements in a Tree are arranged in multiple levels.
In the Tree data structure, the topmost node is known as a root node. Each node contains some data, and data can be of
any type.
binary tree, each node in a tree can have utmost two child nodes. Here, utmost means whether the node has 0 nodes, 1
node or 2 nodes.
Java TreeSet class implements the Set interface that uses a tree for storage. ava TreeSet class contains unique elements
only like HashSet.
Java TreeSet class access and retrieval times are quite fast.
Java TreeSet class doesn't allow null elements.
Java TreeSet class is non-synchronized.
Java TreeSet class maintains ascending order.
TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-Black Tree. Therefore, operations such
as a search, remove, and add consume O(log(N)) time. The reason behind this is there in the self-balancing tree
Synchronization of The TreeSet : ClassAs already mentioned above, the TreeSet class is not synchronized. It means if more than one
thread concurrently accesses a tree set, and one of the accessing threads modify it, then the synchronization must be done manually
It is usually done by doing some object synchronization that encapsulates the set. However, in the case where no such object is
found, then the set must be wrapped with the help of the Collections.synchronizedSet() method. It is advised to use the method
during creation time in order to avoid the unsynchronized access of the set.
TreeSet treeSet = new TreeSet();
Set syncrSet = Collections.synchronziedSet(treeSet);
TreeSet(Collection<? extends E> c) It is used to build a new tree set that contains the elements of
the collection c.
TreeSet(Comparator<? super E> comparator) It is used to construct an empty tree set that will be sorted
according to given comparator.
Methods of Java TreeSet Class
boolean add(E e)- It is used to add the specified element to this set if it is not already present.
NavigableSet subSet(E fromElement, boolean It returns a set of elements that lie between the given
fromInclusive, E toElement, boolean toInclusive) range.
SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given
range which includes fromElement and excludes
toElement.
Example Program -1
import java.util.*;
class TreeSet3{
public static void main(String args[]){
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(24);
set.add(66);
set.add(12);
set.add(15);
System.out.println("Lowest Value: "+set.pollFirst());
System.out.println("Highest Value: "+set.pollLast());
Lowest Value: 12
Highest Value: 66
}
}
Example Program -2
import java.util.*;
class TreeSet5{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("E");
System.out.println("Intial Set: "+set);
System.out.println("Head Set: "+set.headSet("C"));
System.out.println("TailSet: "+set.tailSet("C"));
}
}
Intial Set: [A, B, C, D, E] Head Set: [A, B] SubSet: [A, B, C, D] TailSet: [C, D, E]
Java TreeSet Example: Book
To add user-defined objects in TreeSet, you need to implement the Comparable interface.
import java.util.*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
// implementing the abstract method
public int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
}
public class TreeSetExample {
public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
//Adding Books to TreeSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing TreeSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Binary Search Tree
A binary search tree follows some order to arrange the elements. In a Binary search tree, the value of left node must be smaller than
the parent node, and the value of right node must be greater than the parent node. This rule is applied recursively to the left and
right subtrees of the root.
Searching an element in the Binary search tree is easy as we always have a hint that which subtree has the desired element.As
compared to array and linked lists, insertion and deletion operations are faster in BST.