Posts

Showing posts with the label Collections Framework

Iterator and Enumeration - Differences Explained

In this article, I will be comparing the Iterator and Enumeration interfaces. I will be explaining the similarities and differences between Iterator and Enumeration. Definitions Both Iterator and Enumeration are interfaces defined in the Java Collection framework. You can use both to loop through the elements of a Collection. Let us first understand how they work   Iterator Iterator is an interface defined in the Java Collection framework. You can use it to loop through the elements of a collection. The following code demonstrates this: List<Integer> numbers = Arrays.asList(2,4,6,8,10); Iterator<Integer> itr = numbers.iterator(); while (itr.hasNext()) { System.out.print(itr.next()+" "); } This code uses an Iterator to loop through the elements in a List and print them. Iterator.hasNext() method returns true if there are more elements in the collection. The iterator.next() method returns the next element in the collection. So this code prints the following ou...

How to sort a List in Descending order

In this article, I will be demonstrating how you can sort a List in descending order. In order to see how to sort a List, you can refer to this blog post.   Approach 1 – Using Collections.reverse The Collections class has a utility method called reverse.  You can use this to sort a List in descending order. The following code demonstrates this: private static void usingCollectionsReverse() { List<Integer> input = Arrays.asList(15,12,34,11,93,21,64); System.out.println("Before sorting:"+input); Collections.sort(input); Collections.reverse(input); System.out.println("After sorting:"+input);} Here, the code first invokes the Collection.sort . This sorts the List in ascending order. Then the code invokes the Collections.reverse method to reverse the List. So this code prints the following output: Before sorting:[15, 12, 34, 11, 93, 21, 64]After sorting:[93, 64, 34, 21, 15, 12, 11] Approach 2 – Using Collections.reverseOrder There is an overloaded version of ...

How to sort a List on objects in Java using a Compator

In this blog post, I will be explaining how you can sort a List of objects in Java using the Comparator interface. Input List Suppose, there is a Person class as follows: public class Person {private String firstName;private String lastName;private int age;public Person(String firstName,String lastName,int age){this.firstName=firstName;this.lastName=lastName;this.age=age;//getter and setter methods public String toString(){ return firstName+" "+lastName+":"+age; }}} And you have a list of Person objects as follows: Person person1 = new Person("Mickey", "Mouse",34); Person person2 = new Person("Donald", "Duck",45); Person person3 = new Person("Peppa", "Pig",12); List<Person> people = new ArrayList<Person>(); people.add(person1); people.add(person2); people.add(person3); Using Comparator to sort in increasing order of age And suppose you want to sort them in the increasing order of a...

How to reverse a List in Java

In this blog post, I will be explaining how you can reverse a Set or List via Java.  Consider the following code snippet: package learnjava.collections;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class ReverseDemo {public static void main(String[] args) {List<Integer>inputList = new ArrayList<Integer>();inputList.add(5);inputList.add(15);inputList.add(20);inputList.add(25);List<Integer>reverserdList1 = reverseList1(inputList);List<Integer>reverserdList2 = reverseList2(inputList);System.out.println("Input List is "+inputList);System.out.println("reverserdList using method1 "+reverserdList1);System.out.println("reverserdList using method2 "+reverserdList2);}private static List<Integer> reverseList2(List<Integer>inputList ){List<Integer> reverserdList = new ArrayList<Integer>();for(int i =inputList.size()-1;i >=0;i--){reverserdList.add(inputList.get(i));}return reverse...

How to convert a Java list to an array

In this blog post, I will be explaining how you can convert a Java list to an array. To see how to convert an Array to a List, click here .   There are a couple of ways to do this. Consider the following code snippet: public class ListToArrayDemo {public static void main(String[] args) {//Method 1List<Integer> list = Arrays.asList(5,3,11,15,9);Object[] objects = list.toArray();//Method 2Integer[] integers = new Integer[list.size()];integers = list.toArray(integers);//Method 3Integer[] integers2 = new Integer[list.size()];for(int i = 0; i < list.size();i++){integers2[0] = list.get(0);}}} This code shows 3 ways to convert a List having integers to an array. Though I’ve used an Integer List here, you can use a List that stores any type of data. Method 1  The toArray method available on the list interface is used in this approach. This method returns an Object array. The downside to this approach is that the resultant array is an Object array. So you loose the type of d...

How to find if two lists are exactly the same

In this blog post, I will be explaining how you can check if 2 lists are exactly the same. Consider the following code snippet: public class CompareLists {public static void main(String[] args) {List<Integer> list1 = Arrays.asList(3,9,5,15,11);List<Integer> list2 = Arrays.asList(3,9,5,15,11);boolean matches = false;if(list1.size() == list2.size()){matches = list1.containsAll(list2);}if(matches)System.out.println("List1 and List2 are the same");elseSystem.out.println("List1 and List2 are different");}}   Here, we have 2 lists, list1 and list2 . First, we are comparing the size of the lists.  If they are different, then it means that the two lists are different. However, if the sizes are the same, then the code invokes the list.containsAll method. This method returns true if the list on which it is invoked contains all the elements in the list passed in. So when you run this code, it will print the following output: List1 and List2 are the same Now l...

How to create a list with data without using list.add multiple times

In this blog post, I will be explaining how you can easily create a List of elements with some data. Consider the following code snippet: public static void main(String[] args) {List<Integer> input = new ArrayList<Integer>();input.add(3);input.add(9);input.add(5);input.add(15);input.add(11);}   The code above creates a new ArrayList called input. It invokes the add method multiple times in order to add data to this list. This code does not look very clean. The above code can be re-written as follows: List<Integer> input = Arrays.asList(3,9,5,15,11); Here, the Arrays.asList method is invoked.  The Arrays class has methods for manipulating arrays. It also has the asList method. This returns a List which is backed by the specified array.So in this case, the  Arrays.asList returns an ArrayList  that has the elements specified.

How to sort a List via Java

In this blog post, I will be explaining how you can sort a list via Java.  Consider the following code snippet: package learnjava.collections;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class SortDemo {public static void main(String[] args) {List<Integer> input = new ArrayList<Integer>();input.add(3);input.add(9);input.add(5);input.add(15);input.add(11);System.out.println("Before sorting:"+input);Collections.sort(input);System.out.println("Before sorting:"+input);}}   This code uses the Collections.sort method. The Collections class contains static utility methods that operate on collections like List, Set etc.  When the Collections.sort method is invoked, it sorts the input list in ascending order. The return type of this method is void, so the input list is modified for sort. This code will print the following output: Before sorting:[3, 9, 5, 15, 11]Before sorting:[3, 5, 9, 11, 15]

ArrayList Vs LinkedList

In this blog post, I will be comparing the ArrayList and LinkedList classes. I will be explaining how they are similar, how they are different and when you should use which.   Similarities: Both are Collections and implement the List interface Both are used to store a dynamic number of elements (Primitive or Object type) Differences ArrayList uses an array data structure internally to store the data. A LinkedList on the other hand, uses a doubly linked list internally as the data structure to store data. If you are not familiar with what a Linked List data structure is, you can refer this link . When you need to insert or delete data from the bottom of the List, an ArrayList is faster. If you need to insert or delete an element from the middle of the list,  a LinkedList is faster. An ArrayList  uses an array to store the data internally. So when you insert or delete an element from the bottom of the list, this does not affect the array. However if you insert or delete an element...

What are Iterators in Java?

Java provides an interface called Iterator that is used to iterate over or loop through the elements in a collection. You can use an iterator on any Collection interfaces or any of its sub interfaces like List or Set .   Consider the following code snippet: public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i &amp;lt; 10; i ++){ list.add(i+2); } Iterator<Integer> itr = list.iterator(); while (itr.hasNext()){ int i = itr.next(); System.out.println("i="+i); } }   This code demonstrates how you can use iterator to iterate over a List. Here, we are iterating over a list of integers. But you can use it to iterate over any data type. The iterator method on the list interface returns an iterator instance. In the iterator variable declaration, we need to specify the data type that the iterator will iterate over. In this case, we are specifying Integer.  Once we obtain an iterator, we ca...

How to shuffle the elements in a List via Java

In this blog post, I will be explaining how you can shuffle list via Java.  Consider the following code snippet: package learnjava.collections;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class ShuffleDemo {public static void main(String[] args) {List<Integer> input = new ArrayList<Integer>();input.add(3);input.add(9);input.add(5);input.add(15);input.add(11);System.out.println("Before shuffling:"+input);Collections.shuffle(input);System.out.println("After shuffling:"+input);}}   This code uses the Collections.shuffle method. The Collections class contains static utility methods that operate on collections like List, Set etc.  When the Collections.shuffle  is invoked, it shuffles the input list randomly. The return type of this method is void, so the input list is modified. When you run this code, it will print output similar to the following: Before shuffling:[3, 9, 5, 15, 11]After shuffling:[15, 11, 3, 9, 5]...

How to find the maximum and minimum number in a List

In this blog post, I will be demonstrating how you can find the largest and smallest number in an array. Consider the following code snippet: package learnjava.collections;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class MaxMinDemo {public static void main(String[] args) {List<Integer> input = new ArrayList<Integer>();input.add(3);input.add(9);input.add(5);input.add(15);input.add(11);System.out.println("Biggest element in the list is:"+Collections.max(input));System.out.println("Smallest element in the list is:"+Collections.min(input));}}   This code uses the Collections.max and Collections.min methods. The Collections class contains static utility methods that operate on collections like List, Set etc.  The Collections.max  method returns the greatest element in the list according to the natural order or sorting. Similarly, the Collections.min returns the smallest element in the list according to the na...

How to convert a List to a Set

In this blog post ,I will be showing you how you can convert a List to a Set. Consider the following code snippet: public class ListToSetDemo {public static void main(String[] args) {List<Integer> list = Arrays.asList(5,3,11,15,9);//Method 1Set<Integer> set = new HashSet<Integer>(list);System.out.println("Set is "+set);//method 2Set<Integer> set2 = new HashSet<Integer>();set2.addAll(list);System.out.println("Set is "+set2);}} This code demonstrates two ways to convert a List to a Set. Method 1 Here, we are creating a new HashSet . We are invoking the constructor that accepts a Collection object. Here, we are passing in the input list to this constructor.   Method 2 Here again, we are creating a new HashSet . However, we are using the default constructor. We are then invoking the addAll method and passing in the input list.   When you run this code, it will print the following output: Set is [3, 5, 9, 11, 15]Set is [3, 5, 9, 1...

How to remove duplicate elements from a List

In this blog post, I will demonstrate how to remove the duplicates from a List. There are several ways to do this.   Looping throw the List and creating new List The following code snippet demonstrates this approach: public static List<String> removeDuplicates1(List<String> list){List<String> newList = new ArrayList<String>();for(String s:list){if(!newList.contains(s))newList.add(s);}return newList;}   A new List is created. A for loop is used to iterate throw the input List. An if condition is used to check if the new List has each element in the input List and if not, it is added to the new List.   Using a Set The following code snippet demonstrates this approach: public static List<String> removeDuplicates2(List<String> list){Set<String> set = new HashSet<String>();set.addAll(list);List<String> newList = new ArrayList<String>();newList.addAll(set);return newList;} Here, a Set is created. This is added all the ...

What is the difference between a Set and List?

A very common question asked in Java interviews is to explain the difference between a Set and a List . So,in this post I’m going to explain this in detail. What is common between Set and List? Before I start with the differences, let me explain what is common between the two. Both Set and List are sub interfaces of the Collection interface in the java.util package. Both store a group of elements, however they differ slightly in the way they store data.   So what are the differences? Duplicates A List allows duplicate elements i.e. the same element can be present more than once. A Set on the other hand does not allow duplicates. So if the same element is added again, it will overwrite the previous value of the element. Ordering of Elements Also a List is ordered i.e. elements in a list are stored in the order in which they are inserted & this order is maintained. The List interface has a method called add. It adds object sequentially to the list, so the first object ...

How to convert an Array to a List

If you have a non primitive array type, you can use the following code to convert it to a list: public class ArrayToListConverter {public static void main(String args[]){Integer[] intArr = {2,4,6,8,10};List<Integer> intList = new ArrayList<Integer>();//Method 1 - Using for loopfor(int i:intArr){intList.add(i);}//Method 2 - Via Arrays.asListintList = Arrays.asList(intArr);//} Method 1 Here, we are manually iterating through the elements in the list and adding them to an int array. Method 2  Here, we are using the Arrays.asList method. This returns a list corresponding to the array passed in. Note that this method wont work if the array is of primitive type like this: int[] intArr = {2,4,6,8,10};