Posts

Showing posts with the label Java-Collection-Examples

Difference between Comparator and Comparable

Java has two interfaces that you can use for sorting custom objects. These are the Comparator and Comparable interface. In this article, I will be explaining the differences between the two. Basic difference between Comparator and Comparable The main difference between the Comparator and Comparable interface is that you can use Comparator  to compare two independent objects. The Comparable on the other hand is used to compare the current object with another object. Consider the following Person class: public class Person { private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; }} Suppose you want to sort Person objects on the basis of the age fields. Let us understand how you can achieve this using both Comparator and Comparable. Sorting Using Comparator In order to sort using Comparator, you will first need to create a class that implements the Comparator interface.  The following code demonstrates this...

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 ...

Java TreeSet and HashSet similarities and differences

Java TreeSet and HashSet are implementations of the Set interface. Often you may have wondered, whether to choose HashSet or TreeSet and which is faster. In this article, I will be comparing the HashSet and TreeSet classes in Java. HashSet and TreeSet Similarities Duplicates not allowed Since both HashSet and TreeSet implement the Set interface, they do not allow duplicates. So consider the following code: Set<String> hashSet = new HashSet<String>(); hashSet.add("Mango"); hashSet.add("Mango"); Set<String> treeSet = new TreeSet<String>(); treeSet.add("Mango"); treeSet.add("Mango"); System.out.println("Number of elements in Hashset:"+hashSet.size()); System.out.println("Number of elements in Treeset:"+treeSet.size()); When you execute this code, it will print the following output: Number of elements in Hashset:1Number of elements in Treeset:1  Not Thread-Safe Both HashSet and ...

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]

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 ...

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};