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

Select Menu