How to concatenate 2 List in Java

We have seen situation that we need to merge or concatenate 2 Lists of same type into single List. To do this instead of iterating all elements and adding to new List we can use addAll() function to concatenate 2 List items. There are two types of addAll() function in Java.
How to concatenate 2 List in Java
  • First we can merge all elements at the end of List.
  • Second we can insert all of the elements from specified position of List.
Lets see both types by simple example


import java.util.ArrayList;
import java.util.List;

public class ListTest {

 public static void main(String[] args) {
  
  List<String> list1 = new ArrayList<String>();
  list1.add("one");
  list1.add("two");
  list1.add("three");
  
  List<String> list2 = new ArrayList<String>();
  list2.add("four");
  list2.add("five");
  list2.add("six");
  
  // First type merging at the end of list
  list1.addAll(list2);
 
  System.out.println("First Type : "+list1);
  
  list1.clear();
  list1.add("one");
  list1.add("two");
  list1.add("three");
  
  // Second type merging at index(1)
  list1.addAll(1, list2);
  
  System.out.println("\nSecond Type : "+list1);
 }
}

OUTPUT:


First Type : [one, two, three, four, five, six]

Second Type : [one, four, five, six, two, three]

How to Iterate Map key and value

We can Iterate Map's key and values in lot of ways like getting keySet or by getting entrySet or by using Iterator interface. Lets see all these ways with simple example.
How to Iterate Map key and value


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("2", "two");
  map.put("3", "three");
  map.put("1", "one");
  map.put("4", "four");
  map.put("5", "five");
  

  System.out.println("Using entrySeT() ---- ");
  
                   for (Map.Entry<String, String> myMap : map.entrySet()) {
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }

  
  System.out.println("\nUsing keySet() ---- ");
  
  for (Object myKey : map.keySet()) {
   System.out.println(myKey.toString() + " : " + map.get(myKey));
  }

  
  System.out.println("\nUsing Iterator interface ---- ");
  
  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


Using entrySeT() ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Using keySet() ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Using Iterator interface ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Difference between Hashtable, HashMap, TreeMap and LinkedHashMap

 
Map is one of the most important data structures and when we talk about Map all these 4 implementation classes (Hashtable, HashMap, TreeMap and LinkedHashMap) are most used. Hashtable, HashMap and LinkedHashMap are directly implements Map interface, but TreeMap implements Map interface through implementing SortedMap. Below are the few differences between these classes
Difference between Hashtable, HashMap, TreeMap and LinkedHashMap
  • HashMap implemented as same as Hashtable except it is unsynchronized and permits null. As common both HashMap and Hashtable won't have any ordering on keys or values.
  • TreeMap implemented based on red-black tree structure and it follows natural ordering on key. 
  • LinkedHashMap is a subclass of HashMap and inherits all properties of HashMap class and additionally its ordering will based on insertion order.
NOTE:
  • If we use any Map implementation classes and if the key is user-defined class Object then we need to override hashcode() and equals() methods. 
  • Next when we use TreeMap, by default they are sorted by keys. If we use user-defined class Object for key, then to compare with each other we need to implement Comparable interface.

Next lets see simple examples for each classes. 

Hashtable:


import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new Hashtable<String, String>();
  map.put("1", "one");
  map.put("2", "two");
  map.put("3", "three");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


5 : five
4 : four
3 : three
2 : two
1 : one


HashMap:


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("1", "one");
  map.put("2", "two");
  map.put("3", "three");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUPTUT:


3 : three
2 : two
1 : one
5 : five
4 : four


TreeMap:


import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new TreeMap<String, String>();
  map.put("2", "two");
  map.put("3", "three");
  map.put("1", "one");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


1 : one
2 : two
3 : three
4 : four
5 : five


LinkedHashMap:


import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new LinkedHashMap<String, String>();
  map.put("2", "two");
  map.put("3", "three");
  map.put("1", "one");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


2 : two
3 : three
1 : one
4 : four
5 : five

Implementing Queue in Java

 
Queue is a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first to be removed. Suppose if a queue contains 4 elements and 5th element added at back and if we need to remove that element then we need to remove all front 4 elements first. As like Stack implementation in java we can implement Queue Data Structure and also we have operations in Queue like enqueue(), dequeue(), front(), isempty() etc.,
Implementing Queue in Java

enqueue() - Insert element in front of the Queue.

dequeue() - Return front element and remove same element from the Queue.

front() - Same as dequeue() returns front element but same element won't be removed from the Queue.

clean() - cleans the Queue.



Lets see simple example to implement Queue using ArrayList and using Generics for holding any datatype.



import java.util.ArrayList;
import java.util.List;

public class MyQueue <E>{

 private List<E> list = null;
 
 public MyQueue() {
  list = new ArrayList<E>();
 }

 public void enqueue(E val){
  list.add(val);
 }
 
 public E dequeue(){
  E val = null;
  if(list.size() > 0){
   val = list.get(0);
   list.remove(0);
  }  
  return val;
 }
 
 public boolean isEmpty(){
  if(list.size() == 0)return true;
  else return false;
 }
 
 public int size(){
  return list.size();
 }
 
 public E front(){
  E val = null;
  if(list.size() > 0){
   val = list.get(0);
  }  
  return val;
 }
 
 public void clean(){
  list = new ArrayList<E>();
 }
 
 @Override
 public String toString() {
  return list.toString();
 }
}


Our Queue class is ready and we can test with below code.


public class TestMyQueue {

 public static void main(String[] args) {
  
  MyQueue<String> queue = new MyQueue<String>();
  
  int qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //ENQUEUE
  queue.enqueue("one");
  queue.enqueue("two");
  queue.enqueue("three");
  queue.enqueue("four");
  queue.enqueue("five");
  System.out.println("5 ELEMENTS ADDED IN QUEUE");
  qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //QUEUE
  System.out.println("QUEUE      : "+queue);
  
  //FRONT
  System.out.println("FRONT       : "+queue.front());
  
  //DEQUEUE
  System.out.println("DEQUEUE        : "+queue.dequeue());
    
  qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //FRONT
  System.out.println("FRONT       : "+queue.front());
  
  //ISEMPTY
  System.out.println("EMPTY      : "+queue.isEmpty());
  
  //CLEAN
  queue.clean();
  System.out.println("QUEUE CLEANED");
  
  //ISEMPTY
  System.out.println("EMPTY      : "+queue.isEmpty());
  
 }
}


OUTPUT:


QUEUE SIZE     : 0
5 ELEMENTS ADDED IN QUEUE
QUEUE SIZE     : 5
QUEUE             : [one, two, three, four, five]
FRONT             : one
DEQUEUE         : one
QUEUE SIZE      : 4
FRONT             : two
EMPTY             : false
QUEUE CLEANED
EMPTY             : true






Implement Stack in Java

 
In our earlier tutorial we have seen how to use default Stack class in Java and their methods like push, pop, peek etc., Suppose in any of the interview if interviewer asked us to implement our own Stack class which holds any type of data like Integer, String or even other datatypes. Then we need to go with Generics and need to implement our Stack class.

Lets see simple example to implement Stack using ArrayList and using Generics for holding any datatype.


import java.util.ArrayList;

public class MyStack <E> {

 ArrayList<E> list = null;
 
 public MyStack() {
  list = new ArrayList<E>();
 }
 
 public E push(E val){
  list.add(val);
  return val;
 }
 
 public E pop(){
  E val = list.get(list.size()-1);
  list.remove(list.size()-1);
  return val;
 }
 
 public E peek(){
  E val = list.get(list.size()-1);
  return val;
 }

 public int size(){
  return list.size();
 }
 
 public int search(E val){
  int id = -1;
  if(list.contains(val)){
   id = list.indexOf(val);
  }
  return id;
 }
 
 public boolean empty(){
  if(list.size() == 0) return true;
  else return false;
 }
 
 @Override
 public String toString() {
  return list.toString();
 }
}


Our Stack class is ready and we can test with below code.


public class TestMyStack {

 public static void main(String[] args) {
  
  MyStack<Integer> stack = new MyStack<Integer>();
  
  int stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //PUSH
  stack.push(11);
  stack.push(21);
  stack.push(31);
  stack.push(41);
  stack.push(51);
  
  stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //STACK
  System.out.println("STACK      : "+stack);
  
  //PEEK
  System.out.println("PEEK       : "+stack.peek());
  
  //POP
  System.out.println("POP        : "+stack.pop());
  
  
  stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //PEEK
  System.out.println("PEEK       : "+stack.peek());
  
  //EMPTY
  System.out.println("EMPTY      : "+stack.empty());
  
  //SEARCH
  System.out.println("SEARCH     : "+stack.search(21));
  
  //SEARCH
  System.out.println("SEARCH     : "+stack.search(700));
 }
}


OUTPUT:


STACK SIZE : 0
STACK SIZE : 5
STACK        : [11, 21, 31, 41, 51]
PEEK          : 51
POP            : 51
STACK SIZE : 4
PEEK          : 41
EMPTY        : false
SEARCH      : 1
SEARCH      : -1



Stack class in java

 
Basically Stack represents last-in-first-out (LIFO) ordering of objects. In Java Stack extends Vector and defines its own five methods along with default methods which allow a vector to be treated as a stack and those methods are
Stack class in java

push()
- Pushes the element or object into the stack and it returns the same element. 

pop()
- Removes the first element from the stack and it returns the same element. 
empty()

- Checks whether the stack is empty or not. Returns true if stack is empty else false.

peek()
- Similar to pop(), return first element from the stack but it won't remove the element. 

search()
- Searches for the element from the stack and returns the offset of the element if found else returns -1. 

Lets see simple example in java how to use Stack class.


import java.util.Stack;

public class StackTest {

 public static void main(String[] args) {
  
  Stack<Integer> stack = new Stack<Integer>();
  
  int stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //PUSH
  stack.push(11);
  stack.push(21);
  stack.push(31);
  stack.push(41);
  stack.push(51);
  
  stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //STACK
  System.out.println("STACK      : "+stack);
  
  //PEEK
  System.out.println("PEEK       : "+stack.peek());
  
  //POP
  System.out.println("POP        : "+stack.pop());
  
  
  stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //PEEK
  System.out.println("PEEK       : "+stack.peek());
  
  //EMPTY
  System.out.println("EMPTY      : "+stack.empty());
  
  //SEARCH
  System.out.println("SEARCH     : "+stack.search(21));
  
  //SEARCH
  System.out.println("SEARCH     : "+stack.search(700));
 } 
}


OUTPUT:


STACK SIZE  : 0
STACK SIZE  : 5
STACK         : [11, 21, 31, 41, 51]
PEEK           : 51
POP            : 51
STACK SIZE : 4
PEEK          : 41
EMPTY        : false
SEARCH      : 3
SEARCH      : -1