Skip to main content

Posts

Showing posts with the label Collections API

Java : How to sort Array List based on Custom Order

How to sort Array List using Custom Order On many occasions we need to sort an array list or linked list based on custom logic. Suppose you have a Quiz application and you want to return questions based on a custom question id. e.g Request : ids = [ 88, 21, 43, 15, 64, 35 ] When you will fetch the Questions from Database you will be using a query something like below select * from question where id in (?) This will give you questions ordered by id by default. So to covert it in same order as requested order you can use view plain copy to clipboard print ? // ids = [ 88, 21, 43, 15, 64, 35 ]    // questions = new ArrayList<Question>();     Collections.sort(questions,  new  Comparator<Question>() {         @Override          public   int  compare(QuestionDto q1, QuestionDto q...

How to add objects in a HashMap

Points To Remember HashMap saves objects in form of key-value pair in form of Entry object (Map.Entry). We can use any object as a key on which hashCode() and equals() can be applied. We cannot use primitive datatypes as keys or values. We can have only one value corresponding to a key , other values will get overridden. A hashMap can contain a single null key . Initial size of a HashMap is 16 and its load factor is 0.75 after this HashMap gets rehashed. Program : Adding Objects to HashMap Below program shows how to save key-value pairs as entry objects in a HashMap. We use put()  method to store key-value pairs in a Hashmap. import java.util.HashMap; class Test{ public static void main(String args[]){ // Declaring and Initializing a HashMap HashMap<String, String> map = new HashMap<String, String>(); // Adding Objects TO HashMap map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key...

How to Iterate over HashMap Collection in Java

Points To Remember A HashMap contains objects in key-value pair. We can use enumeration, iterator , for loop (jdk v1.5 onwards) and lamda expression ( jdk v1.8) We can add values to HashMap using put(key,value). We can get all keys by . keySet()  and value of a key using .get(key) Method 1: Traverse A HashMap using "for" loop The below example shows how we can traverse a HashMap in java using advanced for loop. import java.util.HashMap; class Test{ public static void main(String args[]){ HashMap<String, String> map = new HashMap<String, String>(); map.put("key 1","value 1"); map.put("key 2","value 2"); map.put("key 3","value 3"); map.put("key 4","value 4"); map.put("key 5","value 5"); // Iterating Map using advanced for loop available from jdk v1.5 onwards // Iterating over Values for(String value : map.values()){ System.out.p...

What is a TreeSet in Java ?

Points To Remember TreeSet is ordered and sorted Set. TreeSet extends AbstractSet and implements NavigableSet. Objects are stored in ascending order based on natural ordering. You can even define your sorting rules for sorting a TreeSet using constructors with Comparable or Comparator. It is fast for Accessing/Retrieving objects but slow for Adding/Removing objects.  Constructor : TreeSet TreeSet(); // Default Constructor TreeSet(Collection<? extends E> c); //TreeSet from Collection C TreeSet(Comparator<? super E> comp); // TreeSet with custom ordering as per Comparator TreeSet(SortedSet<E>ss); //TreeSet that contains the elements of ss. Example : TreeSet Implementation Suppose we have a Set of Tourists from different countries and we want to sort them according to their names.(Right now we can just neglect the country of the tourists). import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<String> tourists =...

How HashSet works internally in Java ??

Points To Remember HashSet returns unordered and unsorted values. HashSet contains only the unique values. HashSet maintains an internal HashMap to provide uniqueness.  How Set maintains Uniqueness ?? The following program shows how we add new values to a set. import java.util.Set; import java.util.HashSet; class SetImpl{ public static void main(String args[]){ Set<object> set = new HashSet<object>(); set.add(100); set.add("Java"); set.add("String"); set.add("Java"); set.add("Java"); System.out.println(set); } } Output of the program is [100, String, Java] Now, the question is how does Set maintains  uniqueness. The answer is that Set internally maintains a HashMap. Surprised ?? If you open the implementation of HashSet in the java api you will get the following implementation. public class HashSet extends AbstractSet implements Set , Cloneable, java.io.Serializable { private transient HashMap ...

Sorting objects using Comparable Interface.

Points To Remember Comparable is an interface and is available in java.lang package. A class implementing it should override compareTo() method. compareTo(Object obj) method returns  negative integer if object obj is greater than the object with  whom it is compared. 0 if both the objects have same values or are same. positive integer if object obj have is less than the object with whom it is compared. While overriding compareTo() method we must check If the two objects belong to the same class, else throw ClassCastException. If the two objects are not null, if either is null then throw NullPointerException. We need not implement this class if we need to sort an array or list with objects like string, integers etc.  Example:  Sorting a list of objects using Comparable Interface Suppose we have a class Book with fields name and price and we need to sort the objects based on the name of the book, if the name of the book is same then we sort the book object based on ...

Difference between Comparator and Comparable Interfaces

Difference between Comparator and Comparable Comparator Comparable It is available in java.util package. It is available in java.lang package. We need to override compare()  method. We need to override compareTo() method. It takes two arguments as parameters. public int compare(Object obj1,Object obj2 )  It takes only one argument as a parameter. public int compareTo(Object obj) Its primary use is where we need to write the comparing logic outside the class which has to be compared.   It is used when we need to compare the instance of an object with a given object. Comparing logic is inside the class that needs to be compared.   this reference is not made while comparing objects this  reference is used to compare the object.  It is used for comparing objects based on any logic. It is mostly used for comparing objects based on the natural ordering. Points To Remember Both compareTo() and compare() methods return int value. Both compareTo() and...

How to sort objects using Comparator Interface

Points To Remember Comparator is an interface and is available in java.util package. A class that implement Comparator interface must override its compare() method.  We use Comparator when we have to write logic for comparing object of a class outside that class. compare(Object e1, Object e2): Can be called like compare(e1, e2) compare(Objecte obj1, Object obj2) method returns zero if the objects are equal. compare(Objecte obj1, Object obj2) method returns a positive value if obj1 is greater than obj2. compare(Objecte obj1, Object obj2) method returns a negative value if obj1 is smaller than obj2. It should throw ClassCastException if object types of e1 and e2 are not comparable. It should throw NullPointerException if either e1 or e2 or both passed are null. Syntax for using Comparator interface. First we need a class for which we need to write the sorting logic(how to compare objects of this class). Then we need to create a new class that will do this comparin...

What is the Difference between Enumeration and Iterator

Points To Remember In java 1.0, there were two primary collection classes HashMap and Vector. Enumeration was a class in Java 1.0 to Iterate through these collection classes.(They are not the enum types.) Iterator was introduced in Java 1.2 Difference between Enumeration and Iterator. Enumeration Iterator It was introduces in Java v1.0 It was introduced in java v1.2 Enumeration does not have remove() method Iterator has remove() method Enumeration provides a read only iteration over collection Iterator provides iteration over collections along with manipulation of objects like adding and removing from object. Enumeration is less safe and secure Iterator is more secure and safe, when multiple thread work on same object, it does not allow any thread to modify the object and throws ConcurrentModificationException. Enumeration has lengthy method names like hasMoreElements() nextElements() Iterator have short method names like hasNext() next() Enumeration is used when we want to iterate Col...

How does a HashMap works internally in Java ??

Points To Remember HashMap implements the Map Interface. It works on the principles of hashing.  It stores and retrieves data in a key value pair. HashMap can have only one key as a null element. HashMap stores both key and value in form of Entry object  Map.Entry.  Initial capacity of HashMap is 16. (Since jdk 1.7 we can have HashMap with initial capacity as 0). Default load Factor of a HashMap is 0.75, after this a HashMap gets rehashed.  Q1 : How does HashMap work internally ?  We add data to the HashMap in key-value pair, by method put(key, value).  When we do this, the hashCode() method is called upon the key to return a hashcode, this hashcode is an integer value 16 digit long by default. This hashcode is then used by the HashMap's internal hashing method to find a bucket location  to store the Entry object. At this bucket location both key and value is saved in the bucket. Since we know that different objects can result into the same hashcode,...