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);
}
}
Tuesday, September 16, 2014
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.
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
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.

3) Inserts Performance: LinkedList add method gives
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:
2) Search (get method) operations are fast in Arraylist (
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.
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:
- Both ArrayList and LinkedList are implementation of List interface.
- 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.
- Both these classes are non-synchronized and can be made synchronized explicitly by using
Collections.synchronizedListmethod. - 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
To:
- Better Exception Handling (Multiple exceptions handling to eliminate duplication of codes)
Before:
Try with resources:
Before:
- 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
- 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-statementTry 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:
·
abstract a method or class that can not be instantiated, and
which may define methods to be overwritten.
·
class keyword used to specify a class.
·
extends used to indicate the super-class that a subclass is
extending.
·
final makes it impossible to extend a class, override a
method, or reinitialize a variable.
·
implements used to indicate the interfaces that a class will use.
·
interface keyword used to specify an interface.
·
native indicates a method is written in a platform-dependant
language, such as C.
·
new used to instantiate an object by invoking the
constructor method.
·
static makes a method or variable belong to a class.
·
synchronized indicates that a method can be accessed by only one
thread at a time.
·
transient indicates which variables are not to have their data
written to an ObjectStream.
·
volatile indicates 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
|
Subscribe to:
Comments (Atom)