Java program to reverse ArrayList elements

  • How to reverse an ArrayList in java.
  • By using Collections.reverse() method we can reverse ArrayList in java.



#1: Java Example program to reverse ArrayList 

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.Collections;

  4. public class ReverseArrayList {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview questions
  8. * Description: Java Example program to reverse an ArrayList
  9. *
  10. */
  11. public static void main(String[] args) {
  12. ArrayList<String> arrayList= new ArrayList<>();
  13. arrayList.add("Apple");
  14. arrayList.add("Banana");
  15. arrayList.add("Orange");
  16. Collections.reverse(arrayList);
  17. System.out.println(arrayList);
  18. }

  19. }


Output:

  1. [Orange, Banana, Apple]


#2: Java Example program to print arraylist in reverse order 


reverse arraylist in java example program

How to convert list to set in java with example program

  • Java program to convert list to set.
  • Convert ArrayList of string to HashSet in java example program
  • How to convert List to Set in java 
  • Set<String> strSet = new HashSet<String>(arrList);
  • HashSet having a constructor which will take list as an argument.
  • Lets see how to convert list to Set using java program.



#1: Java Example Program to Convert List to Set.


  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = new HashSet<String>(arrList);
  18. System.out.println(strSet);

  19. }

  20. }

Output:

  1. [Java, Example Program, List to String]

  • Using java.util.stream we can convert List to set in java 8
  • We can use java 8 java.util.stream.Collectors
  • arrList.stream().collect(Collectors.toSet());

#2: Java Example program to convert List to Set using java 8.

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.Set;
  4. import java.util.stream.Collectors;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = arrList.stream().collect(Collectors.toSet());
  18. System.out.println(strSet);

  19. }

  20. }


Output:

java convert list to set

Java 8 stream filter method example program

  • We can use java 8 stream class filter method to filter the values from a list /map in java
  • By Using filter() and collect() methods of stream class we can achieve this.
  • Lets see an example program to filter value from list without using java 8 streams and with java 8 stream filter.



#1: Java Example program to filter . remove value from list without using java 8 stream

  1. package com.instanceofjava.filtermethodjava8

  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;

  5. /**
  6.  * @author www.Instanceofjava.com
  7.  * @category interview programs
  8.  * 
  9.  * Description: Remove value from list without using java 8 stream filter method
  10.  *
  11.  */
  12. public class fillterListJava8{
  13. private static List<String> filterList(List<String> fruits, String filter) {
  14.         List<String> result = new ArrayList<>();
  15.         for (String fruit : fruits) {
  16.             if (!filter.equals(fruit)) { 
  17.                 result.add(fruit);
  18.             }
  19.         }
  20.         return result;
  21.     }
  22. public static void main(String[] args) {
  23. List<String> fruits = Arrays.asList("apple", "banana", "lemon");
  24.  
  25. System.out.println("Before..");
  26.  
  27. for (String str : fruits) {
  28.             System.out.println(str);    
  29.         }
  30.  
  31.         List<String> result = filterList(fruits, "lemon");
  32.         System.out.println("After..");
  33.         for (String str : result) {
  34.             System.out.println(str);    
  35.         }
  36. }
  37. }

Output:
  1. Before..
  2. apple
  3. banana
  4. lemon
  5. After..
  6. apple
  7. banana

#2: Java Example program to filter . remove value from list using java 8 java.util.stream

  1. package com.instanceofjava.java8;

  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.stream.Collectors;

  6. /**
  7.  * @author www.Instanceofjava.com
  8.  * @category interview programs
  9.  * 
  10.  * Description: Remove value from list using java 8 stream filter method
  11.  *
  12.  */

  13. public class filterMethodOfStream {

  14. public static void main(String[] args) {
  15. List<String> fruits = Arrays.asList("apple", "banana", "lemon");
  16. String value="lemon";
  17. List<String> result = fruits.stream()                
  18.                 .filter(line -> !value.equals(line))     
  19.                 .collect(Collectors.toList());             
  20.         result.forEach(System.out::println); 
  21.        
  22.         for (String str : result) {
  23.             System.out.println(str);    
  24.         }
  25. }

  26. }






Output:


java 8 stream filter method

Benefits of arraylist in java over arrays


Disadvantages of arrays:




Advantages / Benefits of arraylist in java:

  • We have some disadvantages of arrays like arrays are fixed in length. and we need to mention size of the array while creation itself.
  • So we have some advantages of arraylist when compared to arrays in java.
  • Here  the major advantages of arraylist over arrays.

1.ArrayList is variable length
  • One of the major benefit of arraylist is it is dynamic in size. we can increase as well as decrease size of the arraylist dynamically.
  • Resizable.
Program #1: Java example program to explain the advantages of ArrayList: resizable


  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.  public static void main(String[] args) {
  11.         
  12.         ArrayList<Integer> list = new ArrayList<Integer>();
  13.          
  14.         list.add(1);
  15.  
  16.         list.add(2);
  17.  
  18.         list.add(3);
  19.  
  20.         System.out.println(list.size());      
  21.         list.add(4);
  22.         list.add(5);
  23.  
  24.         System.out.println(list.size());     
  25.         list.remove(1);
  26.  
  27.         System.out.println(list.size());    
  28.     }
  29. }

Output:

  1. 3
  2. 5
  3. 4
  • In the above program by using add and remove methods of ArrayList we can change the size of the ArrayList

2.Default initial capacity is 10.
  • One of the major benefit of arraylist is by default it will assign default size as 10.
  • Whenever we create object of ArrayList constructor of ArrayList assign default capacity as 10.

3.Insert and remove elements also at particular position of  ArrayList
  • Another advantage of ArrayList is it can add and remove elements at particular position.

Program #2: Java example program to explain the advantages of ArrayList:Add and remove elements at particular position.

  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<Integer> list = new ArrayList<Integer>();
  13.          
  14.         list.add(1);
  15.  
  16.         list.add(2);
  17.  
  18.         list.add(3);
  19.  
  20.         System.out.println(list);
  21.  
  22.         list.add(0,4);
  23.         
  24.         System.out.println(list);
  25.         
  26.         list.add(2,5);
  27.  
  28.       
  29.         System.out.println(list);
  30.         list.remove(3);
  31.         
  32.         System.out.println(list);
  33.         System.out.println(list.size());    
  34.     }
  35. }

Output:

  1. [1, 2, 3]
  2. [4, 1, 2, 3]
  3. [4, 1, 5, 2, 3]
  4. [4, 1, 5, 3]
  5. 4


4.Add any type of data into ArrayList.
  • We can add different type of objects in to the ArrayList.
  • In this scenario avoid mentioning generics while declaring ArrayList.

Program #3: Java example program to explain the advantages of ArrayList: Add any type of Object.

arrayList advantages in java

5.Traverse in both directions.
  • We can traverse both direction using List Iterator.

Program #4: Java example program to explain the advantages of ArrayList: Traverse in both directions.
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.ListIterator;
  5.  
  6. public class ArrayListExample {
  7.     /**
  8.     * Advantages of arrayList over arrays in java
  9.     * @author www.instanceofjava.com
  10.     */
  11.     public static void main(String[] args) {
  12.         
  13.         ArrayList<String> list = new ArrayList<String>();
  14.          
  15.         list.add("ArrayList Advantages");
  16.  
  17.         list.add("ArrayList benefits");
  18.         
  19.         list.add("ArrayList in java");
  20.  
  21.         ListIterator iterator = list.listIterator();
  22.         
  23.         System.out.println("**ArrayList Elements in forward direction**");
  24.          
  25.         while (iterator.hasNext())
  26.         {
  27.             System.out.println(iterator.next());
  28.         }
  29.          
  30.         System.out.println("**ArrayList Elements in backward direction**");
  31.          
  32.         while (iterator.hasPrevious())
  33.         {
  34.             System.out.println(iterator.previous());
  35.         } 
  36.     }
  37. }
 Output:

  1. **ArrayList Elements in forward direction**
  2. ArrayList Advantages
  3. ArrayList benefits
  4. ArrayList in java
  5. **ArrayList Elements in backward direction**
  6. ArrayList in java
  7. ArrayList benefits
  8. ArrayList Advantages

6.ArrayList allows Multiple null values
  • We can add multiple null elements to ArrayList

Program #5: Java example program to explain the benefits of ArrayList: Add null elements
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<String> arraylist = new ArrayList<String>();
  13.          
  14.         arraylist.add(null);
  15.  
  16.         arraylist.add(null);
  17.         
  18.         arraylist.add(null);
  19.  
  20.         System.out.println(arraylist);
  21.     }
  22. }

Output:

  1. [null, null, null]

7.ArrayList allows to add duplicate elements
  • We can add duplicate elements into arrayList
Program #6: Java example program to explain the advantages of ArrayList: Add any type of Object.
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<String> arraylist = new ArrayList<String>();
  13.          
  14.        arraylist.add("ArrayList");
  15.  
  16.         arraylist.add("ArrayList");
  17.         
  18.         arraylist.add("ArrayList");
  19.  
  20.         System.out.println(arraylist);
  21.     }
  22. }

Output:

  1. [ArrayList, ArrayList, ArrayList]

8.ArrayList has many methods to manipulate stored objects.
  • ArrayList has many methods to manipulate stored objects.
  • addAll(), isEmpty(). lastIndexOf() etc.

How to Sort list of objects by multiple fields in java

  • In order to compare objects we have comparable and comparator in java.
  • If you want to do custom sorting we will use comparator in java
  • We need to use different comparators for sorting objects by different fields.
  • And using Collections.sort(List, Comparator).
  • We can sort list of class objects by using cmparator.
  • By this we can compare two objects field by field. actually many.
  • Lets see an example program to sort list of student objects by name rollno and marks using comparator. Here comparator means we need to develop sorting logic in separate class which implements comparator interface and overrides compare() method.  
Program 1: Write a java example program to sort list of objects 

Student class:

  • Define a class as student add variables.
  • Define a constructor to assign values to variables.
  • Define a toString() method to print each variable value inside object values when we print object.

  1. package com.sortobjects;
  2. /**
  3.  * How to sort list of class objects
  4.  * @author www.instanceofjava.com
  5.  */
  6.  
  7. public class Student {
  8.     
  9.     String name;
  10.     int Rollno;
  11.     float marks;
  12.  
  13. Student(String name, int Rollno, float marks){
  14.         
  15.         this.name=name;
  16.         this.marks=marks;
  17.         this.Rollno=Rollno;
  18. }
  19.  
  20.     public String getName() {
  21.         return name;
  22.     }
  23.     public void setName(String name) {
  24.         this.name = name;
  25.     }
  26.     public int getRollno() {
  27.         return Rollno;
  28.     }
  29.     public void setRollno(int rollno) {
  30.         Rollno = rollno;
  31.     }
  32.     public float getMarks() {
  33.         return marks;
  34.     }
  35.     public void setMarks(float marks) {
  36.         this.marks = marks;
  37.     }
  38.     
  39. public String toString() {
  40.         return ("Name:"+name+"\tRollNo:"+Rollno+"\tMarks"+marks);
  41.     }
  42.  
  43. }

 NameComparator:

  • This class sort list of student class objects by name.

  1. package com.sortobjects;
  2. import java.util.Comparator;
  3.  
  4. public class NameComparator implements Comparator<Student>{
  5.     /**
  6.      * How to sort list of class objects
  7.      * @author www.instanceofjava.com
  8.      */
  9.     @Override
  10.     public int compare(Student obj1, Student obj2) {
  11.      
  12.          return obj1.getName().compareTo(obj2.getName());
  13.     }
  14.    
  15.  
  16. }

 RollNoComparator :
  • This class sort list of student class objects by Rollno.


  1. package com.sortobjects;
  2. import java.util.Comparator;
  3.  
  4. public class RollNoComparator implements Comparator<Student>{
  5.     /**
  6.      * How to sort list of class objects
  7.      * @author www.instanceofjava.com
  8.      */
  9.     @Override
  10.     public int compare(Student obj1, Student obj2) {
  11.      
  12.          return ((Integer)obj1.getRollno()).compareTo((Integer)obj2.getRollno());
  13.     }
  14.    
  15.  
  16. }

MarksComparator:
  • This class will compare list of student class objects by marks

  1. package com.sortobjects;
  2. import java.util.Comparator;
  3. public class MarksComparator implements Comparator<Student>{
  4.     /**
  5.      * How to sort list of class objects
  6.      * @author www.instanceofjava.com
  7.      */
  8.     @Override
  9.     public int compare(Student obj1, Student obj2) {
  10.          return ((Float)obj1.getMarks()).compareTo((Float)obj2.getMarks());
  11.     }
  12.  
  13. }

SortListObjects:
  •  Take a test class 
  • Create arraylist object and add Student objects with different values into list.
  • Using Collections.Sort(List,FiledComparator) pass corresponding comparator class in order to sort multiple fields of a class.


  1. package com.sortobjects;
  2. mport java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5.  
  6. /**
  7.  * How to sort list of class objects
  8.  * @author www.instanceofjava.com
  9.  */
  10.  
  11. public class SortListObjects {
  12.  
  13.      public static void main(String[] args){
  14.         
  15.         
  16.         List<Student> studentlst= new ArrayList<Student>();
  17.         
  18.         studentlst.add(new Student("Saisesh",1,80));
  19.         studentlst.add(new Student("Vinod",2,90));
  20.         studentlst.add(new Student("Ajay",3,95));
  21.         
  22.         System.out.println("** Before sorting **:");
  23.          
  24.         for (Student student : studentlst) {
  25.             System.out.println(student);
  26.         }
  27.         Collections.sort(studentlst,new NameComparator());
  28.         
  29.         System.out.println("** After sorting **");
  30.          
  31.         for (Student student : studentlst) {
  32.             System.out.println(student);
  33.         }
  34.     }
  35.  
  36. }
 Output:



sort list of objects java


  •  Like this we can compare list of objects by Rollno, and marks aslo. Please practice this example by sorting rollno and marks and check output. if you have any doubts then leave a comment.

 Chained comparator:
  • We can use chained comparator to sort list of class objects by multiple fields by passing multiple comparators.
  • java collections sort multiple comparators
  • The below program is example of chained comparator java


  1. package com.sortobjects;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Comparator;
  5. import java.util.List;
  6.  
  7. public class StudentChainedComparator implements Comparator<Student> {
  8.     
  9.      private List<Comparator<Student>> listComparators;
  10.      
  11.     
  12.         public StudentChainedComparator(Comparator<Student>... comparators) {
  13.             this.listComparators = Arrays.asList(comparators);
  14.         }
  15.      
  16.         @Override
  17.         public int compare(Student student1, Student student2) {
  18.             for (Comparator<Student> comparator : listComparators) {
  19.                 int result = comparator.compare(student1, student2);
  20.                 if (result != 0) {
  21.                     return result;
  22.                 }
  23.             }
  24.             return 0;
  25.         }
  26.  
  27.        
  28.  
  29. }
 
Java comparator multiple fields example:


  • Lets see an example of java comparatorchain in java


java comparator multiple fields example

Deep copy in java example program

  • Creating a copy of the object can be done in two ways 
  • Shallow copy and deep copy. we have already discussed about shallow copy
  • Shallow copy in java example program
  • In shallow copy of object only object reference will be copied and if we change any data inside object changes will reflect in cloned object also this means both are referring to same object.
  •  


Deep copy / Deep cloning in  Java

  • In deep copy completely a new object will be created with same data.
  • If we change the data inside original object wont reflect in deeply cloned object.

deep cloning vs shallow cloning in java



Program #1: Java example program to demonstrate deep copy / deep cloning

Sample :

  1. package com.shallowcopyvsdeppcopy;

  2. public class Sample {
  3. int a;
  4. int b;

  5. Sample (int a, int b){
  6.     this.a=a;
  7.     this.b=b;
  8. }

  9. }

Empclone :
  1. package com.shallowcopyvsdeppcopy;
     
  2. public class empclone implements Cloneable {
  3.  
  4.     Sample s;
  5.     int a;
  6.     
  7.     empclone(int a, Sample s){
  8.         this.a=a;
  9.         this.s=s;
  10.        
  11.     }
  12.      
  13. public Object clone()throws CloneNotSupportedException{ 
  14.        return new empclone(this.a, new Sample(this.s.a,this.s.a));
  15. }  
  16.            
  17.     
  18. public static void main(String[] args) {
  19.      
  20.         empclone a= new empclone(2, new Sample(3,3));
  21.         empclone b=null;
  22.     
  23.  try {
  24.              b=(empclone)a.clone();
  25.            
  26.  } catch (CloneNotSupportedException e) {
  27.             // TODO Auto-generated catch block
  28.             e.printStackTrace();
  29.         }
  30.         System.out.println(a.s.a);
  31.         System.out.println(b.s.a);
  32.        
  33.         a.s.a=12;
  34.         System.out.println(a.s.a);
  35.         System.out.println(b.s.a);
  36. }
  37.  
  38. }

OutPut:
  1. 3
  2. 3
  3. 12
  4. 3

What is the difference between shallow copy and deep copy:
  • When we create a shallow copy of the object only reference will be copied
  • When we create deep copy of the object totally new object with same data will be created. 
  • Shallow copy and deep copy will be done by using Cloneable  interface in java. 

Difference between Collections and Collection in java with example program

In Java, "Collection" refers to the interface that defines the basic properties and behaviors of a collection, while "Collections" is a utility class that provides static methods for working with collections.

The Collection interface is part of the Java Collections Framework and it is a root interface for all the collections. It defines the basic properties and behaviors that all collections should have, such as adding and removing elements, checking the size of the collection, and so on.
It includes List, Set and Queue interfaces.

On the other hand, the Collections class is a utility class that provides various static methods for working with collections, such as sorting, reversing, and searching. It also provides methods for creating unmodifiable collections, which are collections that cannot be modified after they are created.

Here are some examples of how we can use the Collections class:

To sort a List:

List<Integer> myList = new ArrayList<>();
myList.add(3);
myList.add(1);
myList.add(2);
Collections.sort(myList);

To reverse an array:

Collections.reverse(myList);

To create an unmodifiable collection:

List<Integer> unmodifiableList = Collections.unmodifiableList(myList);

It's worth noting that, the Collections class only provides static methods, it does not provide any instance methods. So, you can't create an object of the Collections class.

  • Famous java interview question: difference between collections and collection in java
  • Major difference between Collection and Collections is Collection is an interface and Collections is a class. 
  • Both are belongs to java.util package
  • Collection is base interface for list set and queue.
  • Collections is a class and it is called utility class.
  • Collections utility class contains some predefined methods so that we can use while working with Collection type of classes(treeset, arraylist, linkedlist etc.)
  • Collection is base interface for List , Set and Queue.



Collection vs Collections

  1. public interface Collection<E> 
  2. extends Iterable<E>


  1. public class Collections
  2. extends Object


difference between collections and collection in java

  • Collections utility class contains static utility methods so that we can use those methods by using class name without creating object of Collections class object
  • Lest see some methods of Collections class.


  1. addAll: public static <T> boolean addAll(Collection<? super T> c,T... elements)
  2. reverseOrder: public static <T> Comparator<T> reverseOrder()
  3. shuffle: public static void shuffle(List<?> list)
  4. sort:public static <T extends Comparable<? super T>> void sort(List<T> list)
How to Relate Collection and Collections
  • ArrayList is a Collection type of class means it is implementing Collection interface internally
  • Now lets see a java example program to sort ArrayList of elements using Collections.sort() method.

  1. public class ArrayList<E>
  2. extends AbstractList<E>
  3. implements List<E>, RandomAccess, Cloneable, Serializable


1.Basic Java example program to sort arraylist of integers using Collections.sort() method

  1. package com.javasortarraylistofobjects;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class SortArrayListExample{
  8.  
  9. public static void main(String[] args) {
  10.   
  11. //create an ArrayList object
  12.  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  13.        
  14.  //Add elements to Arraylist
  15. arrayList.add(10);
  16. arrayList.add(7);
  17. arrayList.add(11);
  18. arrayList.add(4);
  19. arrayList.add(9);
  20. arrayList.add(6);
  21. arrayList.add(2);
  22. arrayList.add(8);
  23. arrayList.add(5);
  24. arrayList.add(1);
  25.         
  26.         
  27.  System.out.println("Before sorting ArrayList ...");
  28.  Iterator itr=arrayList.iterator();
  29.         
  30. while (itr.hasNext()) {
  31.  
  32. System.out.println(itr.next());
  33.      
  34. }
  35.  
  36.        
  37.  /*
  38.  To sort an ArrayList object, use Collection.sort method. This is a
  39.   static method. It sorts an ArrayList object's elements into ascending order.
  40. */
  41.   Collections.sort(arrayList);
  42.      
  43.   System.out.println("After sorting ArrayList ...");
  44.        
  45.     
  46.         
  47. Iterator itr1=arrayList.iterator();
  48.         
  49. while (itr1.hasNext()) {

  50. System.out.println(itr1.next());
  51.             
  52. }
  53.     
  54.   
  55. }
  56. }
     


Output:

  1. Before sorting ArrayList ...
  2. 10
  3. 7
  4. 11
  5. 4
  6. 9
  7. 6
  8. 2
  9. 8
  10. 5
  11. 1
  12. After sorting ArrayList ...
  13. 1
  14. 2
  15. 4
  16. 5
  17. 6
  18. 7
  19. 8
  20. 9
  21. 10
  22. 11

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
Select Menu