Tuesday, September 16, 2014

How to sort a map based on the values or keys

Here is an example of how to sort a map based on the values or keys:

public class TestMapComparator {

    public static final Comparator<Map.Entry<Integer,String>> valueComparator = new Comparator<Map.Entry<Integer,String>>(){
        public int compare(Map.Entry<Integer,String> map1, Map.Entry<Integer,String> map2){
             
                 return map1.getValue().compareTo(map2.getValue());
        }
       
    };
   
    public static final Comparator<Map.Entry<Integer,String>> keyComparator = new Comparator<Map.Entry<Integer,String>>(){
        public int compare(Map.Entry<Integer,String> map1, Map.Entry<Integer,String> map2){
             
                 return map1.getKey()-map2.getKey();
        }
       
    };
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1, "D");
        map.put(2, "A");
        map.put(3, "B");
        map.put(4, "C");
        System.out.println(map);
        List list = new LinkedList(map.entrySet());
        Collections.sort(list,TestMapComparator.valueComparator);
        System.out.println(list);
        Collections.sort(list,TestMapComparator.keyComparator);
        System.out.println(list);
       

    }

}

Sunday, September 14, 2014

Difference between ArrayList and LinkedList in Java


ArrayList and LinkedList both implements List interface and their methods and results are almost identical. However there are few differences between them which make one better over another depending on the requirement.

 

ArrayList Vs LinkedList

 

1) Search: ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n).
Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.
2) Deletion: LinkedList remove operation gives O(1) performance while ArrayList gives variable performance: O(n) in worst case (while removing first element) and O(1) in best case (While removing last element).
Conclusion: LinkedList element deletion is faster compared to ArrayList.
Reason: LinkedList’s each element maintains two pointers (addresses) which points to the both neighbor elements in the list. Hence removal only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be removed. While In ArrayList all the elements need to be shifted to fill out the space created by removed element.

A doubly-linked list whose nodes contain three fields: an integer value, the link to the next node, and the link to the previous node.

3) Inserts Performance: LinkedList add method gives O(1) performance while ArrayList gives O(n) in worst case. Reason is same as explained for remove.
4) Memory Overhead: ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighbor nodes hence the memory consumption is high in LinkedList comparatively.
There are few similarities between these classes which are as follows:
  1. Both ArrayList and LinkedList are implementation of List interface.
  2. They both maintain the elements insertion order which means while displaying ArrayList and LinkedList elements the result set would be having the same order in which the elements got inserted into the List.
  3. Both these classes are non-synchronized and can be made synchronized explicitly by using Collections.synchronizedList method.
  4. The iterator and listIterator returned by these classes are fail-fast (if list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException).

When to use LinkedList and when to use ArrayList?

1) As explained above the insert and remove operations give good performance (O(1)) in LinkedList compared to ArrayList(O(n)). Hence if there is a requirement of frequent addition and deletion in application then LinkedList is a best choice.
2) Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so If there are less add and remove operations and more search operations requirement, ArrayList would be your best bet.

Friday, August 15, 2014

New Features in JDK 5, JDK 6, JDK 7, JDK 8, JDK 9, JDK 10, JDK 11

JDK 1.5

- Generics

- Metadata

- Autoboxing and unboxing

- Enumerations

- The swing of JDK1.5 has an all-new look

- Varags

- Enhanced for each loop

- Concurrency utilities


JDK 1.6


- Improved performance(JDK 1.6 is faster )

- JavaScript that is integrated and included in the entire platform

- JDBC4 implementation

- Enhanced web services support(Client and Core Java Architecture for XML-Web Services (JAX-WS) 2.0 APIs)

- API for XML digital signature services for secure web services

- Support for Java Architecture for XML Binding (JAXB) 2.0

- improved security enhancements (Native platform security, Java Authentication and Authorization Service (JAAS), the New Smart Card I/OAPI, native security services)



JDK 7 
(July 2011)

- String in switch
- Improved Type Inference for generics instance creation

From:
Map<String, List<String>> map = new HashMap<String, List<String>>();
To:
Map<String, List<String>> map = new HashMap<>();

- Better Exception Handling (Multiple exceptions handling to eliminate duplication of codes)
Before:

try {

    // execute code that may throw 1 of the 3 exceptions below.

} catch(SQLException e) {
    logger.log(e);

} catch(IOException e) {
    logger.log(e);

} catch(Exception e) {
    logger.severe(e);
}
After:
try {

    // execute code that may throw 1 of the 3 exceptions below.

} catch(SQLException | IOException e) {
    logger.log(e);

} catch(Exception e) {
    logger.severe(e);
}
- Automatic resource management in try-statement
Try with resources:
Before:
BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
After:
try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
} 

- JDBC enhancement 

JDK8 
(March 2014)

- Language-level support for Lambda Expressions

- PermGen completely removed and replaced with a new space called Metaspace

- New Date and Time API
- Small VM

JDK 9
September 22, 2016

- Jshell = Java + REPL
- G1 will be the new default garbage collector
Http2Client, Java Platform Module System (JPMS),  
Multi-release jar files, Stack Walking API, Private methods in an interface, Process API updates, Collection API updates, Stream API improvements, and etc.
Below are the few differences between Java 8 and Java 9
  • In Java 8 and earlier versions, the top-level component is the package. It places a set of related types (classes, interfaces, enums, and etc) into a group, and also contains a set of resources whereas Java 9 introduces a new component: module, which can be used to place a set of related packages into a group, and also another new component: the module descriptor, module-info.java file.
  • Java 8 applications use packages as a top-level component whereas Java 9 applications use modules as a top-level component.
  • Each Java 9 module has only one module with one module descriptor whereas Java 8 package doesn't build multiple modules into a single module.


Saturday, May 24, 2014

Class, Method, and Variable Modifiers






The following are class, method, or variable modifiers:

·        abstracta method or class that can not be instantiated, and which may define methods to be overwritten.
·        classkeyword used to specify a class.
·        extendsused to indicate the super-class that a subclass is extending.
·        finalmakes it impossible to extend a class, override a method, or reinitialize a variable.
·        implementsused to indicate the interfaces that a class will use.
·        interfacekeyword used to specify an interface.
·        nativeindicates a method is written in a platform-dependant language, such as C.
·        newused to instantiate an object by invoking the constructor method.
·        staticmakes a method or variable belong to a class.
·        synchronizedindicates that a method can be accessed by only one thread at a time.
·        transientindicates which variables are not to have their data written to an ObjectStream.
·        volatileindicates a variable may change out of sync due to its usage in threads.



Variables
Methods
Classes
Access Modifiers



private
x
x

protected
x
x

none (default)
x
x
x
public
x
x
x




Special Modifiers(Not Access Modifiers)



abstract

x
x
final
x
x
x
native

x

static
x
x
x
synchronized

x
x
transient
x


volatile
x