Posts

Showing posts with the label Collection framework

How to sort list of objects in java with examples

We could achieve list of objects sorting in java by using sort() method which is available under Collections class as well as by using Comparable and Comparator  interfaces. Comparable and Comparator are two interfaces in java used to sort list of objects. These interfaces are available under java.util package along with Collections  class and other classes and interfaces. Comparable interface contains the method of       public int compareTo(Object obj) Comparator interface contains the method of       public int compare(Object obj1, Object obj2) The compare() and compareTo() methods will return negative integer(-1), or zero(0) or positive integer(1). When the first obj1 is less than obj2 method will return negative integer. When obj1 is equals to obj2 will return zero and when obj1 is grater than obj2 it will return positive integer. If it's objects are stored in any Collection classes like ArrayList, HashSet in Array and that time we need to use compare(

Map interface with implementation classes

Map interface stores elements in the form of key-value pairs in java. If the key is provided then its corresponding value can be obtained. Of course, the keys should have unique values. Map interface implemented classes are, HashMap HashTable LinkedHashMap TreeMap Methods of Map implemented classes: value put(key, value) : This method stores key-value pairs. value get(Object key) : This method returns corresponding value when key is given. If the key does not have a value associated with it, then it returns null. Set<K> keySet() : This method, when applied on a map converts it into a Set where only keys will be stored. Collection<V> values() : This method, when applied on a HashMap objects returns all the values of the HashMap into Collection objects. value remove(Object key) : This method removes the key and corresponding value from the map. void clear() : This method removes all the key-value pairs. boolean isEmpty() : This met

Set interface in java with example

Read this article to know what is Set interface and its implemented classes in java with examples programs.  Set interface  represents a group of elements arranged as like an array. Set interface will grown dynamically when the elements are stored into it. Set will not allow duplicate elements to store into it. Set interface implemented classes are, HashSet<T> TreeSet<T> LinkedHashSet<T>           <T> represents the generic type of the storing element in set. Set interface methods: boolean add(Object) : Ensures the Set holds the argument. The Object is added only if it isn't already in the Set. Returns false if the Object was not added to the Set. void clear() : Removes all elements from the Set. boolean contains(Object) : Returns true if the Set contains the argument. boolean isEmpty() : Returns true if the Set contains no elements. Iterator iterator() : Returns an Iterator ob