Remove duplicates from arraylist without using collections

1.Write a Java program to remove duplicate elements from an arraylist without using collections (without using set)




  1. package arrayListRemoveduplicateElements;
  2. import java.util.ArrayList;
  3.  
  4. public class RemoveDuplicates {
  5. public static void main(String[] args){
  6.     
  7.     ArrayList<Object> al = new ArrayList<Object>();
  8.     
  9.     al.add("java");
  10.     al.add('a');
  11.     al.add('b');
  12.     al.add('a');
  13.     al.add("java");
  14.     al.add(10.3);
  15.     al.add('c');
  16.     al.add(14);
  17.     al.add("java");
  18.     al.add(12);
  19.     
  20. System.out.println("Before Remove Duplicate elements:"+al);
  21.  
  22. for(int i=0;i<al.size();i++){
  23.  
  24.  for(int j=i+1;j<al.size();j++){
  25.             if(al.get(i).equals(al.get(j))){
  26.                 al.remove(j);
  27.                 j--;
  28.             }
  29.     }
  30.  
  31.  }
  32.  
  33.     System.out.println("After Removing duplicate elements:"+al);
  34.  
  35. }
  36.  
  37. }



Output:

  1. Before Remove Duplicate elements:[java, a, b, a, java, 10.3, c, 14, java, 12]
  2. After Removing duplicate elements:[java, a, b, 10.3, c, 14, 12]

2. Write a Java program to remove duplicate elements from an array using Collections (Linkedhashset)

  1. package arrayListRemoveduplicateElements;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.List;
  6.  
  7. public class RemoveDuplicates {
  8.  
  9. public static void main(String[] args){
  10.     
  11.     List<String>  arraylist = new ArrayList<String>();
  12.     
  13.     arraylist.add("instanceofjava");
  14.     arraylist.add("Interview Questions");
  15.     arraylist.add("Interview Programs");
  16.     arraylist.add("java");
  17.     arraylist.add("Collections Interview Questions");
  18.     arraylist.add("instanceofjava");
  19.     arraylist.add("Java Experience Interview Questions");
  20.     
  21.     
  22.     System.out.println("Before Removing duplicate elements:"+arraylist);
  23.     
  24.     HashSet<String> hashset = new HashSet<String>();
  25.     
  26.     /* Adding ArrayList elements to the HashSet
  27.      * in order to remove the duplicate elements and 
  28.      * to preserve the insertion order.
  29.      */
  30.     hashset.addAll(arraylist);
  31.  
  32.     // Removing ArrayList elements
  33.     arraylist.clear();
  34.  
  35.     // Adding LinkedHashSet elements to the ArrayList
  36.     arraylist.addAll(hashset );
  37.  
  38.     System.out.println("After Removing duplicate elements:"+arraylist);
  39.  
  40. }
  41.  
  42. }



Output:
 


  1. Before Removing duplicate elements:[instanceofjava, Interview Questions, Interview
  2. Programs, java, Collections Interview Questions, instanceofjava, Java Experience Interview
  3. Questions]
  4. After Removing duplicate elements:[java, Collections Interview Questions, Java Experience
  5. Interview Questions, Interview Questions, instanceofjava, Interview Programs]


arraylist remove duplicates


Iterator and Custom Iterator in java with example programs

Java Iterator 


  • Iterator is an interface which is made for Collection objects like List, Set. It comes inside java.util package and it was introduced in java 1.2 as public interface Iterator. To generate successive elements from a Collection, we can use java iterator. It contains three methods: those are, 

  1. boolean hasNext(): this method returns true if this Iterator has more element to iterate. 
  2. remove(): method remove the last element return by the iterator this method only calls once per call to next().     
  3. Object next() : Returns the next element in the iteration.
  • Every collection classes provides an iterator() method that returns an iterator to the beginning of the collection. By using this iterator object, we can access each element in the collection, one element at a time. In general, to use an iterator to traverse through the contents of a collection follow these steps:
  • Obtain Iterator object by calling Collections’s iterator() method
  • Make a loop to decide the next element availability by calling hasNext() method.
  •  Get each element from the collection by using next() method.
Java Program which explains how to use iterator in java

  • Here is an example demonstrating Iterator. It uses an ArrayList object, You can apply to any type of collection.

  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3.  
  4. public class IteratorExample {
  5.  
  6. public static void main(String args[]) {
  7.  
  8.  // create an array list. But, you can use any collection
  9.  ArrayList<String> arraylist = new ArrayList<String>();
  10.   
  11. // add elements to the array list
  12.  arraylist .add("Raja");
  13.  arraylist .add("Rani");
  14.  arraylist .add("Shankar");
  15.  arraylist .add("Uday");
  16.  arraylist .add("Philips");
  17.  arraylist .add("Sachin");
  18.  
  19. // use iterator to display contents of arraylist
  20.  System.out.println("Original contents of arraylist : ");
  21.  
  22. Iterator<String> itr = arraylist .iterator();
  23.  
  24.   while (itr.hasNext()) {
  25.  
  26.     Object obj = itr.next();
  27.      System.out.print(obj + "\n");
  28.  
  29.      }
  30.  
  31.  }
  32. }

 

Output:

  1. Original contents of arraylist : 
  2. Raja
  3. Rani
  4. Shankar
  5. Uday
  6. Philips
  7. Sachin


  •  Iterator is the best choice if you have to iterate the objects from a Collection. But, Iterator having some limitations.

  • Those are,
  1. Iterator is not index based 
  2.  If you need to update the collection object being iterated, normally you are not allowed to because of the way the iterator stores its position. And it will throw ConcurrentModificationException.
  3. It does not allow to traverse to bi directions.
custom ierator interface in java


  • To overcome these on other side,  we have For-each loop. It was introduced in Java 1.5
  • Advantages of For each loop :
  1. Index Based  
  2. Internally the for-each loop creates an Iterator to iterate through the collection.
  3. If you want to replace items in your collection objects, use for-each loop
  • Consider the following code snippet, to understand the difference between how to use Iterator and for-each loop. 



  1. Iterator<String> itr = aList.iterator();
  2.  
  3. while (itr.hasNext()) {
  4. Object obj = itr.next();
  5. System.out.print(obj + "\n");
  6. }
  7.  
  8. Is same as,
  9.  
  10. For (String str : aList){
  11. System.out.println(str);
  12. }

  • Same code has been rewritten using enhanced for-loops which looks more readable. But enhanced for-loops can’t be used automatically in Collection objects that we implement. Then what do we do? This is where Iterable interface comes in to picture. Only, if our Collection implemented Iterable interface, we can iterate using enhanced for-loops. The advantage of implementing Iterable interface So, we should implement Java Iterable interface in order to make our code more elegant.
  • Here I am going to write a best Practice to develop a custom iterator. Following is the Syntax.


  1. public class MyCollection<E> implements Iterable<E>{
  2.  
  3. public Iterator<E> iterator() {
  4.         return new MyIterator<E>();
  5.     }
  6.  
  7. public class MyIterator <T> implements Iterator<T> {
  8.  
  9.     public boolean hasNext() {
  10.     
  11.         //implement...
  12.     }
  13.  
  14.     public T next() {
  15.         //implement...;
  16.     }
  17.  
  18.     public void remove() {
  19.         //implement... if supported.
  20.     }
  21.  
  22. public static void main(String[] args) {
  23.     MyCollection<String> stringCollection = new MyCollection<String>();
  24.  
  25.     for(String string : stringCollection){
  26.     }
  27. }
  28. }
  29.  
  30. }


  1. package com.instanceofjava.customIterator;
  2.  
  3. public class Book {
  4.  
  5.     String name;
  6.     String author;
  7.     long isbn;
  8.     float price;
  9.    
  10.  
  11.     public Book(String name, String author, long isbn, float price) {
  12.         this.name = name;
  13.         this.author = author;
  14.         this.isbn = isbn;
  15.         this.price = price;
  16.     }
  17.  
  18.  public String toString() {
  19.         return name + "\t" + author + "\t" + isbn + "\t" + ": Rs" + price;
  20.   }
  21.  
  22. }

  1. package com.instanceofjava.customIterator;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import com.pamu.test.Book;
  6. import java.lang.Iterable;
  7.  
  8. public class BookShop implements Iterable<Book> {
  9.  
  10.     List<Book> avail_books;
  11.  
  12.     public BookShop() {
  13.         avail_books = new ArrayList<Book>();
  14.     }
  15.  
  16.     public void addBook(Book book) {
  17.         avail_books.add(book);
  18.     }
  19.  
  20.     public Iterator<Book> iterator() {
  21.         return (Iterator<Book>) new BookShopIterator();
  22.     }
  23.  
  24.     class BookShopIterator implements Iterator<Book> {
  25.         int currentIndex = 0;
  26.  
  27.         @Override
  28.         public boolean hasNext() {
  29.             if (currentIndex >= avail_books.size()) {
  30.                 return false;
  31.             } else {
  32.                 return true;
  33.             }
  34.         }
  35.  
  36.         @Override
  37.         public Book next() {
  38.             return avail_books.get(currentIndex++);
  39.         }
  40.  
  41.         @Override
  42.         public void remove() {
  43.             avail_books.remove(--currentIndex);
  44.         }
  45.  
  46.     }
  47.     
  48.     //main method
  49.     
  50.   public static void main(String[] args) {
  51.  
  52.         Book book1 = new Book("Java", "JamesGosling", 123456, 1000.0f);
  53.         Book book2 = new Book("Spring", "RodJohnson", 789123, 1500.0f);
  54.         Book book3 = new Book("Struts", "Apache", 456789, 800.0f);
  55.  
  56.         BookShop avail_books = new BookShop();
  57.         avail_books.addBook(book1);
  58.         avail_books.addBook(book2);
  59.         avail_books.addBook(book3);
  60.  
  61.         System.out.println("Displaying Books:");
  62.         for(Book total_books : avail_books){
  63.             System.out.println(total_books);
  64.         }
  65.  
  66.     }
  67.  
  68. }

  • Here, we created a  BookShop class which contains books. This class able to use for-each loop only if it implements Iterable interface.Here, we have to provide the implementation for iterator method. we define my BookShopIterator as inner class.
  •  Inner classes will provide more security, So that your class is able to access with in the Outer class and this will achieve data encapsulation.
  • The best reusable option is to implement the interface Iterable and override the method iterator().The main advantage of Iterable is, when you implement Iterable then those object gets support for for:each loop syntax.
  • Execute above program and check output. Practice makes perfect.

Get collection values from hashtable example

1.Basic java collection framework example program to get Value collection from hashtable

  •   Collection values()   This method used to get collection of values
  •  Important note is that if any value is removed from set the original hashtable key also removed
  1. package com.setviewHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5. import java.util.Iterator;
  6. import java.util.Set;
  7.  
  8. public class HashtableExample{
  9.  
  10. public static void main(String[] args) {
  11.   
  12.  //create Hashtable object
  13.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  14.        
  15. //add key value pairs to Hashtable
  16. hashtable.put("1","Java Interview Questions");
  17. hashtable.put("2","Java Interview Programs");
  18. hashtable.put("3","Concept and example program");
  19. hashtable.put("4","Concept and interview Questions");
  20. hashtable.put("5","Java Quiz");
  21. hashtable.put("6","Real time examples");
  22.  
  23.  
  24.  Collection c = hashtable.values();
  25.  System.out.println("Values of Collection created from Hashtable are :");
  26. //iterate through the Set of keys
  27.  
  28.  Iterator itr = c.iterator();
  29.  while(itr.hasNext())
  30.  System.out.println(itr.next());
  31.            
  32.  c.remove("Java Quiz");
  33.            
  34. System.out.println("Elements in hash table");
  35. Enumeration e=hashtable.elements();
  36.         
  37.  
  38.  while (e.hasMoreElements()) {
  39.         System.out.println(e.nextElement());
  40. }    

  41. }
  42.  
  43. }
     



Output:

  1. Values of Collection created from Hashtable are :
  2. Real time examples
  3. Java Quiz
  4. Concept and interview Questions
  5. Concept and example program
  6. Java Interview Programs
  7. Java Interview Questions
  8. Elements in hash table
  9. Real time examples
  10. Concept and interview Questions
  11. Concept and example program
  12. Java Interview Programs
  13. Java Interview Questions


Java Collections example program Get Set view of Keys from Hashtable example

1.Basic java collection framework example program to get set view from hashtable

  • Set keySet()   This method used to get set view of the keys of hashtable
  •  Important note is that if any key is removed from set the original hashtable key also removed
  1. package com.setviewHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5. import java.util.Iterator;
  6. import java.util.Set;
  7.  
  8. public class HashtableExample{
  9.  
  10. public static void main(String[] args) {
  11.   
  12.  //create Hashtable object
  13.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  14.        
  15. //add key value pairs to Hashtable
  16. hashtable.put("1","Java Interview Questions");
  17. hashtable.put("2","Java Interview Programs");
  18. hashtable.put("3","Concept and example program");
  19. hashtable.put("4","Concept and interview Questions");
  20. hashtable.put("5","Java Quiz");
  21. hashtable.put("6","Real time examples");
  22.  
  23.  
  24.  Set st = hashtable.keySet();       
  25.  System.out.println("Set created from Hashtable Keys contains :");
  26. //iterate through the Set of keys
  27.  
  28.  Iterator itr = st.iterator();
  29.  while(itr.hasNext())
  30.  System.out.println(itr.next());
  31.            
  32.  st.remove("1");
  33.            
  34. System.out.println("Elements in hash table");
  35. Enumeration e=hashtable.keys();
  36.         
  37.  
  38.  while (e.hasMoreElements()) {
  39.         System.out.println(e.nextElement());
  40. }    

  41. }
  42.  
  43. }
     



Output:

  1. Set created from Hashtable Keys contains :
  2. 6
  3. 5
  4. 4
  5. 3
  6. 2
  7. 1
  8. Elements in hash table
  9. 6
  10. 5
  11. 4
  12. 3
  13. 2

Java collections interview programming questions

java collections interview programs


Top 100 Java Programs asked in Interviews
  1. Introduction to Collection Framework  

  2. Collection Interface in Java 
  3. Top 20 collection framework interview questions for freshers and experienced

Collection set interface: 

  1. Collection Set Interface    

Hashset Class in Collection framework: (Java programming questions)

  1. Hashset class in java  
  2.  
  3.  
  4.  

LinkedHashSet Class in Collection framework: (Java programming questions)

  1.  

Treeset Class in Collection framework: (Java programming questions)
 
  1.  
  2.  



 Collection List Interface:

  1. Collection List Interface 

ArrayList Class in Collection framework: (Java programming questions)

  1.    
  2.  
  3.  
  4.  
  5. Top 100 Java Programs asked in Interviews 

Map Interface In java

  1. Map interface  

HashMap Class in Collection framework: (Java programming questions)

  1.  
  2.  
  3. Convert keys of a map to List 
  4. Convert Values of a map to List 

 Hashtable Class in Collection framework: (Java interview programming questions)

  1.  
  2.  
  3.  
  4. Top 100 Java Programs asked in Interviews  

Java collections programming interview questions 

  1. Top 20 collection framework interview questions for freshers and experienced  
  2. Collection vs Collections
  3. Difference between enumeration and iterator and list iterator? 
  4. Difference between arraylist and vector 
  5. Differences between HashMap and Hash-table  
  6. Comparable vs Comparator 
  7. Custom iterator in java   
  8. Top 100 Java Programs asked in Interviews 

Remove all elements from hashtable java example

1.Basic java example program to remove all elements from hashtable
  • Object remove(Object key)    This method used to remove value pair from hashtable
  • void clear() this method removes all elements from hashtable
  •  
  1. package com.removevalueHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5.  
  6. public class HashtableExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10.  //create Hashtable object
  11.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  12.        
  13. //add key value pairs to Hashtable
  14. hashtable.put("1","Java Interview Questions");
  15. hashtable.put("2","Java Interview Programs");
  16. hashtable.put("3","Concept and example program");
  17. hashtable.put("4","Concept and interview Questions");
  18. hashtable.put("5","Java Quiz");
  19. hashtable.put("6","Real time examples");
  20.  
  21. Object obj = ht.remove("2");
  22. System.out.println(obj + " Removed from Hashtable");
  23.  
  24. Enumeration e=hashtable.elements();
  25.           
  26.  
  27.  while (e.hasMoreElements()) {
  28.         System.out.println(e.nextElement());
  29. }    
  30. hashtable.clear();
  31.  
  32.  System.out.println("Total key value pairs in Hashtable are : " + hashtable.size());

  33. }
  34.  
  35. }
     



Output:

  1. Java Interview Programs Removed from Hashtable
  2. Real time examples
  3. Java Quiz
  4. Concept and interview Questions
  5. Concept and exampe program
  6. Java Interview Questions
  7. Total key value pairs in Hashtable are : 0

Remove key value pair from hashtable java example

1.Basic java example program to iterate keys of hashtable
  • Object remove(Object key)    This method used to remove value pair from hashtable
  1. package com.removevalueHashtable;
  2.  
  3. import java.util.Hashtable;

  4. import java.util.Enumeration;
  5.  
  6. public class HashtableExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10.  //create Hashtable object
  11.        Hashtable<String,String> hashtable = new Hashtable<String,String>();
  12.        
  13. //add key value pairs to Hashtable
  14. hashtable.put("1","Java Interview Questions");
  15. hashtable.put("2","Java Interview Programs");
  16. hashtable.put("3","Concept and example program");
  17. hashtable.put("4","Concept and interview Questions");
  18. hashtable.put("5","Java Quiz");
  19. hashtable.put("6","Real time examples");
  20.  
  21. Object obj = ht.remove("2");
  22. System.out.println(obj + " Removed from Hashtable");
  23.  
  24. Enumeration e=hashtable.elements();
  25.           
  26.  
  27.            
  28. // display search result
  29.  while (e.hasMoreElements()) {
  30.         System.out.println(e.nextElement());
  31. }    

  32. }
  33.  
  34. }
     



Output:

  1. Java Interview Programs Removed from Hashtable
  2. Real time examples
  3. Java Quiz
  4. Concept and interview Questions
  5. Concept and exampe program
  6. Java Interview Questions
Select Menu