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);
}
}
JavaAndAround
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
|
Friday, August 23, 2013
Eclipse IDE: Snippet/Template
1) Window → Preferences → Java → Code Style→ Code Templates→ Comments ->
Files
Click Edit
and Copy and paste:
*
* Copyright (c), ${date}
* All rights reserved
*
* COMPANY_NAME, INC
* CITY, STATE
* COUNTRY
*
****************************************************************************
* File Name: ${file_name}
*
* $$Log $$
*
* @Autor: ${user} : ${date}
*
*/
2) In Window → Preferences → Java → Code Style→ Code Templates→ Code->
New java File
Click Edit
and Copy and paste:
${filecomment}
${package_declaration}
${typecomment}
${type_declaration}
3) Select: "Automatically add comments for new methods
and types"
So every time you create a new class this header is added
Thursday, April 18, 2013
Polymorphism, Inheritance, Encapsulation
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
In Java programming whole concept of interface is based on Polymorphism and its a famous design principle that to code for interface than implementation to take advantage of Polymorphism and introducing new implementation in future.
In the above example, there are four versions of
Have a look at the following example.
As the method to call is determined at runtime, this is called dynamic binding or late binding.
Every object in Java passes a minimum of two IS-A tests: one for itself and one for Object class
Static polymorphism in Java is achieved by method overloading
Dynamic polymorphism in Java is achieved by method overriding
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
In Java programming whole concept of interface is based on Polymorphism and its a famous design principle that to code for interface than implementation to take advantage of Polymorphism and introducing new implementation in future.
Polymorphism in Java has two types:
Compile time polymorphism (static binding) and Runtime polymorphism (dynamic
binding). Method overloading is an example of static polymorphism, while method
overriding is an example of dynamic polymorphism.
An important example of polymorphism
is how a parent class refers to a child class object. In fact, any object
that satisfies more than one IS-A relationship is polymorphic in nature.
For instance, let’s consider a class
Animal and let Cat be a
subclass of Animal. So, any cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as
its super class Animal.
Note: It’s also legal to say every object in Java is polymorphic
in nature, as each one passes an IS-A test for itself and also for Object class.
Static
Polymorphism:
In Java, static polymorphism is achieved
through method overloading. Method overloading means there are several methods
present in a class having the same name but different types/order/number of
parameters.
At compile time, Java knows which method to
invoke by checking the method signatures. So, this is called compile time polymorphism or static binding. The concept will be
clear from the following example:
class DemoOverload{
public int add(int x, int y){ //method 1
return x+y;
}
public int add(int x, int y, int z){ //method 2
return x+y+z;
}
public int add(double x, int y){ //method 3
return (int)x+y;
}
public int add(int x, double y){ //method 4
return x+(int)y;
}
}
class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3));
//method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
}
}
add methods.
The first method takes two parameters while the second one takes three. For the
third and fourth methods there is a change of order of parameters. The
compiler looks at the method signature and decides which method to invoke for a
particular method call at compile time.Dynamic Polymorphism:
Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called.Have a look at the following example.
class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}
class MotorBike extends Vehicle{
public void move(){
System.out.println(“MotorBike can move and accelerate too!!”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
vh=new Vehicle();
vh.move(); // prints Vehicles can move!!
}
}
It should be noted that in the first call to move(), the
reference type is Vehicle and the object being referenced is MotorBike. So, when a
call to move() is made, Java waits until runtime to determine which object is
actually being pointed to by the reference. In this case, the object is
of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the
object is of the class Vehicle. So, the move() method of Vehicle will be called.As the method to call is determined at runtime, this is called dynamic binding or late binding.
Summary:
An object in Java that passes more than one IS-A tests is polymorphic in natureEvery object in Java passes a minimum of two IS-A tests: one for itself and one for Object class
Static polymorphism in Java is achieved by method overloading
Dynamic polymorphism in Java is achieved by method overriding
Subscribe to:
Comments (Atom)