Sunday, 31 December 2017

Synchronization in Java Multi-Threading

In a multithreaded environment when more than one threads are trying to access a shared resource we need to have some mechanism to ensure that the resource will be used only by one thread at a time. The process by which it is ensured is called synchronization in multi-threading.

How synchronization in Java works

For achieving synchronization in Java concept of monitor is used. Every object created in Java has one associated monitor (mutually exclusive lock). At any given time Only one thread can own the monitor.

Before any thread executes the code which is with in a synchronized method (or synchronized block) compiler provides instructions to acquire the lock on the specified object.

When any thread acquires a lock it is said to have entered the monitor. All other threads which need to execute the same shared piece of code (locked monitor) will be suspended until the thread which initially acquired the lock releases it.

Where can we use synchronized keyword in Java

The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements (also known as synchronized blocks). This can be further divided into use with instance methods and static methods. So, essentially we can have four different ways synchronized keyword can be used.

  • instance method
  • An enclosed code block with in an instance method (Synchronized block).
  • static method
  • An enclosed code block with in a static method.

Refer Static Synchronization in Java Multi-Threading to see how to use synchronization with static method and block and why it is needed.

Let's see where and why we should use a specific type of synchronized method or block.

Synchronized Instance Method

We can synchronize a method by adding synchronized keyword within a method signature.

General Form of synchronized instance method

public synchronized void method_name(parameter_list){
}

Let's see an example code where first we write the code without synchronizing the method and later we have the same code where method is synchronized.

Here we have a class Message whose object will be shared among threads. In class Message there is a method displayMsg and you want one thread to finish printing the message with in the method then only another thread starts executing the method.

Code when synchronized is not used

// This class' shared object will be accessed by threads
class Message{
 public void displayMsg(String msg){
   System.out.println("Inside displayMsg method " + Thread.currentThread().getName());
   System.out.println("**" + msg); 
   try {
      Thread.sleep(10);
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
   System.out.println("*");
 }
}
 
class MyClass implements Runnable{
  Thread t;
  Message msg;
  String message;
  MyClass(Message msg, String str){ 
    this.msg = msg;
    this.message = str;
    // creating threads, 4 threads will be created 
    // all sharing the same object msg
    t = new Thread(this);
    t.start();
  }
  @Override
  public void run() {
     msg.displayMsg(message);
  }
}

public class SynchronizedDemo {
  public static void main(String[] args) {
    Message msg = new Message();
    MyClass mc1 = new MyClass(msg, "I");
    MyClass mc2 = new MyClass(msg, "am");
    MyClass mc3 = new MyClass(msg, "not");
    MyClass mc4 = new MyClass(msg, "synchronized");
  }
}

Output

I got the following output, for you output may differ as it depends upon which thread is picked first.

Inside displayMsg method Thread-0
Inside displayMsg method Thread-3
**synchronized
Inside displayMsg method Thread-1
**am
Inside displayMsg method Thread-2
**not
**I
*
*
*
*

It can be seen how output is all jumbled, because all the 4 threads share the same object and synchronized keyword is not used to ensure that only single thread has the lock on the object and only that thread can execute the method.

Code when synchronized is used

If we synchronize the method only a single thread will access the method at the given time. In that case the displayMsg() method will look like -

class Message{
    public synchronized void displayMsg(String msg){
        System.out.println("Inside displayMsg method " + Thread.currentThread().getName());
        System.out.print("**" + msg);        
        try {
            Thread.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("*");
    }
}

Output

Inside displayMsg method Thread-0
**I*
Inside displayMsg method Thread-1
**am*
Inside displayMsg method Thread-2
**not*
Inside displayMsg method Thread-3
**synchronized*

Now it can be seen how one thread finishes its execution then only another thread starts its execution of the method. Though which thread is picked first is up to the scheduler that's why the message may not print correctly but the point here is that whichever thread enters the synchronized method that finishes then only the next thread starts its execution.

Please note that a synchronized instance method is synchronized on the instance(object) of the class. So, if a class has more than one object then one thread at a time can enter each object's synchronized method.

Synchronized statement(block) in instance method

You don't need to synchronize the whole method, let's say we have a 100 line code method, out of which critical section (shared resource) comprises of 7 lines only then it makes sense to synchronize those 7 lines only rather than the whole method. That way we can improve performance.

synchronized statements must specify the object that provides the intrinsic lock.

General Form of synchronized Synchronized statement (block)

Synchronized(object_reference){
// code block
}

Though it is also possible to synchronize on a string but it is considered a bad idea as "Literal strings within different classes in different packages likewise represent references to the same String object." See this for reference - http://www.javalobby.org/java/forums/t96352.html

If we use the same example used with instance method it can be changed to use synchronized block like this -

//This class' shared object will be accessed by threads
class Message{
    public void displayMsg(String msg){
        System.out.println("Inside displayMsg method " + Thread.currentThread().getName());
        synchronized(this){
            System.out.print("**" + msg);        
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("*");
        }
    }
}

Output

Inside displayMsg method Thread-0
Inside displayMsg method Thread-3
Inside displayMsg method Thread-2
Inside displayMsg method Thread-1
**I*
**am*
**not*
**synchronized*

It can be seen from the output how the first print statement is executed by all the threads as that is not inside the synchronized block. After that only a single thread executes at a time and finishes its execution of the synchronized block only then another thread enters the synchronized block.

Drawback of using Synchronization in Java

Synchronization can introduce thread contention, which occurs when two or more threads try to access the same resource simultaneously and cause the Java runtime to execute one or more threads more slowly, or even suspend their execution. Thread Starvation and livelock are forms of thread contention.

That's all for this topic Synchronization in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  2. Inter-thread Communication Using wait, notify And notifyAll Methods
  3. Difference between ReentrantLock and Synchronized
  4. Deadlock in Java Multi-Threading
  5. ThreadLocal class in Java

You may also like -

Thread Priorities in Java Multi-Threading

When we talk about thread we use terms like concurrent threads or threads executing concurrently. But in reality threads also run one at a time (at least in a single CPU system), threads are given CPU cycle in a time shared manner to simulate concurrency.

The order in which multiple threads will be executed is decided by thread scheduler and thread priority is used by the thread scheduler to make that decision. In this post we'll see what all thread priorities are available in Java multi-threading.

Java Thread Priority

When a thread is created in Java, it inherits its priority from the thread that creates it. Thread's priority can be modified at any time after its creation using the setPriority() method which is a member of Thread class.

General form of setPriority() method

public final void setPriority(int newPriority)

Here newPriority specifies the new thread priority setting for the calling thread. Thread priority in Java ranges from 1 (least important) to 10 (most important) and the default priority level is 5 .

In Java Thread class, three constants are provided to define min, max and default priority of a thread.

     /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

    /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

Let's write some code to see Java thread priority in action. First we'll write a program where no priorities are set so each thread will have the default priority (i.e. 5).

Example code

//This class' shared object will be accessed by threads
class LoopValues implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }      
    }
}

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new LoopValues(), "Thread-1");
        Thread thread2 = new Thread(new LoopValues(), "Thread-2");            
        thread1.start();
        thread2.start();           
        try {
            
            //Wait for the threads to finish
            thread1.join();
            thread2.join();            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }            
        System.out.println("Done with looping values");
    }
}

Output

Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread-2 : 5
Thread-2 : 6
Thread-2 : 7
Thread-2 : 8
Thread-2 : 9
Thread-2 : 10
Thread-1 : 5
Thread-1 : 6
Thread-1 : 7
Thread-1 : 8
Thread-1 : 9
Thread-1 : 10
Done with looping values

Here it can be seen that output has a mix of both the threads. Please note that the output may vary with each run.

Example code with thread priority

Now we'll set the priorities so that one thread has the MAX_PRIORITY (10) and another has the MIN_PRIORITY (1).

//This class' shared object will be accessed by threads
class LoopValues implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }  
    }
}

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new LoopValues(), "Thread-1");
        Thread thread2 = new Thread(new LoopValues(), "Thread-2");      
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread1.start();
        thread2.start();           
        try {
            //Wait for the threads to finish
            thread1.join();
            thread2.join();
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }       
        System.out.println("Done with looping values");
    }
}

Output

Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-1 : 5
Thread-1 : 6
Thread-1 : 7
Thread-1 : 8
Thread-1 : 9
Thread-1 : 10
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread-2 : 5
Thread-2 : 6
Thread-2 : 7
Thread-2 : 8
Thread-2 : 9
Thread-2 : 10
Done with looping values

It can be seen that the thread which has the highest priority finishes first then the second thread starts its execution. Please note that even with this priority setting there may be a mixed output or the thread with the min priority may execute first. That brings us to the next section why we can't rely that much on thread priority in Java.

Caution with thread priority in Java

Thread priority rules are dependent on the host platform (native OS). Host platform may have different priorities for the threads which may be more than what priorities are defined in Java or may be less than that. Java run time system maps the thread priorities to the priority levels of the host platform. So JVM may schedule a thread according to the priority defined in Java multithreading but when that thread actually gets the CPU cycle also depends upon the priorities defined by the host platform.

That's all for this topic Thread Priorities in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Thread States in Java Multi-Threading
  2. Synchronization in Java Multi-Threading
  3. Volatile in Java
  4. What if run() Method Called Directly Instead of start() Method
  5. Java Multi-Threading Interview Questions

You may also like -

Setter-Based Dependency Injection in Spring

In the post Dependency Injection in Spring I have already talked about dependency injection. Dependency Injection exists in two variants.

In this post we'll see one of the type of the dependency injection called Setter-based Dependency Injection in Spring.

In setter-based dependency injection, the Spring IOC container will call setter methods on your beans after invoking a no-arg constructor or no-arg static factory method to instantiate your bean.

The <property> sub-element of <bean> is used for setter injection. If you need to inject an object dependency use ref element, for primitive and String values use value element.

Setter-based Dependency Injection Example Code

Let's see an example to understand it better. There is a PayServiceImpl class which uses Payment Class object to process payment, it has two fields one for Payment class object and another is amount which is an integer field.

Code for PayServiceImpl class, note that it has two fields for which values will be injected using setter dependency injection. For that reason setters are required.

 
public interface IPayService {
 void performPayment();
}
 
public class PayServiceImpl implements IPayService {
 private IPayment payment;
 private int amount;
 
 public void performPayment() {
  payment.executePayment(amount);
 }
 
 public IPayment getPayment() {
  return payment;
 }
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }

 public int getAmount() {
  return amount;
 }
 public void setAmount(int amount) {
  this.amount = amount;
 }
}

Code for CashPayment class

 
public interface IPayment {
 void executePayment(int amount);
}
 
public class CashPayment implements IPayment{
 public void executePayment(int amount) {
  System.out.println("Perform Cash Payment - " + amount); 
 }
}

XML Configuration file (XML file name - appcontext.xml)

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
  <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.maven_spring.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.maven_spring.PayServiceImpl">
      <property name="payment" ref="cashPaymentBean" />
      <property name="amount" value="100" />
  </bean>
  
</beans>

Here you can see that the properties defined in the PayServiceImpl class are used in the name attribute of the property element. Note that same name as given in the class should be used in the configuration file.

To run this you can use the class App -

public class App {
    public static void main( String[] args ){   
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
         ("appcontext.xml");
        IPayService bean = (IPayService) context.getBean("paymentBean");
        bean.performPayment();
        context.close();
    }
}

Note that it is always recommended to use interfaces rather than concrete classes, more so with Spring as whole idea of dependency injection is to have loose coupling and interfaces help in achieving that.

That's all for this topic Setter-Based Dependency Injection in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Reference : Spring framework reference documentation


Related Topics

  1. Run Time Injection Using Spring Expression Language(SpEL)
  2. Using depends-on Attribute in Spring
  3. Spring Example Program Using XML Configuration
  4. Wiring Collections in Spring
  5. Dependency Injection Using factory-method in Spring

You may also like -

>>>Go to Spring Tutorial Page

How to Convert String to Date in Java

When you are displaying date you will convert date to String in required format and print it. But you may need to convert String to date in Java again if -

  1. You have to do any date calculation.
  2. You want to convert date from one format to another. In that case you do need to first convert String date to a date using the same pattern as is used for string and then convert the date again to String in another format.

Using SimpleDateFormat

A tried and tested way to convert String to java.util.Date is to use SimpleDateFormat which also gives you an option to provide customized format. For converting Date to String you use the format method where as to convert from String to Date in Java you will have to use parse method.

Steps to follow

  1. Once you have a date String in a given format you need to create an object of SimpleDateFormat passing pattern as argument which should be similar to the pattern used in the date String.

  2. Call parse method passing date string as an argument which returns the parsed date.

Example code

Let’s see some examples using date strings with different patterns.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate {
 public static void main(String[] args) {
  
  String strDate = "30/06/2017";
  getDate(strDate, "dd/MM/yyyy");
  
  strDate = "Sun, May 8, '16";
  getDate(strDate, "EEE, MMM d, ''yy");
  
  strDate = "Sunday, May 08, 2016";
  getDate(strDate, "EEEE, MMMM dd, yyyy");
  
  strDate = "2016-05-08 AD at 10:13:46 IST";
  getDate(strDate, "yyyy-MM-dd G 'at' hh:mm:ss z");
  
  strDate = "2017-08-12T20:17:46.384Z";
  strDate = strDate.replaceAll("Z", "+0530");
  getDate(strDate, "yyyy-MM-dd'T'hh:mm:ss.SSSZ");
  
 }
 
 private static void getDate(String strDate, String pattern){
  SimpleDateFormat formatter = new SimpleDateFormat(pattern);
  try {
   Date date = formatter.parse(strDate);
   System.out.println("Parsed date " + date);
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Parsed date Fri Jun 30 00:00:00 IST 2017
Parsed date Sun May 08 00:00:00 IST 2016
Parsed date Sun May 08 00:00:00 IST 2016
Parsed date Sun May 08 10:13:46 IST 2016
Parsed date Sat Aug 12 20:17:46 IST 2017

Here note that for the date strDate = "2017-08-12T20:17:46.384Z"; where 'Z' literal is used with the date, you need to remove that literal, it won’t be parsed otherwise and throw exception as follows–

java.text.ParseException: Unparseable date: "2017-08-12T20:17:46.384Z"
 at java.text.DateFormat.parse(Unknown Source)
 at org.netjs.prgrm.StringToDate.getDate(StringToDate.java:31)
 at org.netjs.prgrm.StringToDate.main(StringToDate.java:24)

Here, while replacing it, I have replaced it with the difference with the GMT time i.e. 5 Hrs. 30 Mins (For India). You can replace it with the time zone offset of your requirement or you can find that difference from GMT programmatically.

Converting from one String date format to another

It may happen that you get the date in String format and you have to convert it another format. In that case also first convert the String to date in Java and then again to String in another format.

Example code

Suppose you get the String date in the format dd/MM/yyyy which you will have to convert to format yyyy-MM-dd.

public class StringToDate {
 public static void main(String[] args) {
  
  String strDate = "30/06/2017";
  System.out.println("date in old format - " + strDate);
  SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
  try {
   Date date = formatter.parse(strDate);
   System.out.println("Parsed date - " + date);
   
   formatter = new SimpleDateFormat("yyyy-MM-dd");
   System.out.println("date in new format - " + formatter.format(date));
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
 }
}

Output

date in old format - 30/06/2017
Parsed date - Fri Jun 30 00:00:00 IST 2017
date in new format - 2017-06-30

Using DateFormatter of new Java date time API – Java 8

If you are using Java 8 then you do have better option to convert String to date. If you have an object of type LocalDate, LocalTime or LocalDateTime you can format it using the parse method.

There are two overloaded parse methods :

  • parse(CharSequence text) – Here text argument denotes the date string that has to be parsed. This parse method uses standard ISO_LOCAL_DATE formatter.
  • parse(CharSequence text, DateTimeFormatter formatter) – In this variant of parse method you can pass custom formatter.

Converting String to Date using DateFormatter Java Example code

Let’s see some examples with different formats.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;


public class String2Date {

 public static void main(String[] args) {
  try{
   String strDate = "2011-12-03T10:15:30";
   LocalDateTime localDateTime = LocalDateTime.parse(strDate);
   System.out.println("date " + localDateTime);
   
   strDate = "30/06/2017";
   LocalDate localDate = LocalDate.parse(strDate, 
                           DateTimeFormatter.ofPattern("dd/MM/yyyy"));
   System.out.println("date " + localDate);
   
   strDate = "Sun, May 8, '16";
   localDate = LocalDate.parse(strDate, 
                           DateTimeFormatter.ofPattern("EEE, MMM d, ''yy"));
   System.out.println("date " + localDate);
   
   strDate = "2017-08-12T20:17:46.384Z";
   localDateTime = LocalDateTime.parse(strDate, 
                           DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz"));
   System.out.println("date " + localDateTime);
   
   strDate = "2016-05-08 AD at 10:13:46 IST";
   localDateTime = LocalDateTime.parse(strDate, 
                           DateTimeFormatter.ofPattern("yyyy-MM-dd G 'at' HH:mm:ss z"));
   System.out.println("date " + localDateTime);
   
   strDate = "2017-08-15 03:32:12-0400";  
   ZonedDateTime zonedDateTime = ZonedDateTime.parse(strDate, 
                           DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx"));
   System.out.println("date " + zonedDateTime);
  }catch(DateTimeParseException ex){
   ex.printStackTrace();
  }
  
 }
}

Output

date 2011-12-03T10:15:30
date 2017-06-30
date 2016-05-08
date 2017-08-12T20:17:46.384
date 2016-05-08T10:13:46
date 2017-08-15T03:32:12-04:00

Here note that, for the date time with zone offset strDate = "2017-08-15 03:32:12-0400"; ZonedDateTime is used to correctly parse the string.

That's all for this topic How to convert String to Date in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Convert Date to String in Java
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. How to Format Time in AM-PM Format - Java Program
  4. Difference Between Two Dates - Java Program
  5. How to find last modified date of a file in Java

You may also like -

>>>Go to Java Programs Page

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a scalable concurrent set in Java which uses ConcurrentSkipListMap internally. Though concurrent collections like ConcurrentHashMap and CopyOnWriteArraySet were added in Java 1.5, ConcurrentSkipListSet and the similar map implementation ConcurrentSkipListMap were added in Java 1.6.

ConcurrentSkipListSet in Java

Since ConcurrentSkipListSet implements NavigableSet in Java, it is a sorted set just like TreeSet with added feature of being concurrent. Which essentially means it is a sorted data structure which can be used by multiple threads where as TreeSet is not thread safe.

The elements of the ConcurrentSkipListSet are kept sorted according to their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

ConcurrentSkipListSet provides a constructor that takes a comparator as a parameter.

  • ConcurrentSkipListSet(Comparator<? super E> comparator) - Constructs a new, empty set that orders its elements according to the specified comparator.

ConcurrentSkipListSet implementation provides expected average log(n) time cost for the contains, add, and remove operations and their variants. Insertion, removal, and access operations safely execute concurrently by multiple threads.

No Nulls in ConcurrentSkipListSet

ConcurrentSkipListSet does not permit the use of null elements, because null arguments and return values cannot be reliably distinguished from the absence of elements.

Example Java Code using ConcurrentSkipListSet

Let's see an example where we add some values in a ConcurrentSkipListSet and in the output it can be seen that the elements are sorted. In this example elements are of type String and for String natural ordering is ascending alphabetical order. So when you iterate the set you'll see it is in sorted same way.

Note that ConcurrentSkipListSet like any other set implementation i.e. HashSet can only store unique elements. Also, as mentioned internally it uses ConcurrentSkipListMap so when you call add method of ConcurrentSkipListSet it will in turn call putIfAbsent() method of the concurrentMap, that way element is stored only if it is not there already.

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.concurrent.ConcurrentSkipListSet;

public class CSSDemo {

    public static void main(String[] args) {
        NavigableSet<String> citySet = new ConcurrentSkipListSet<String>();
        citySet.add("New Delhi");
        citySet.add("Mumbai");
        citySet.add("Chennai");
        citySet.add("Hyderabad");
        
        System.out.println("---- Traversing the set-----");
        Iterator<String> itr = citySet.iterator();
        while(itr.hasNext()){
            System.out.println("Value -  " + itr.next());
        }
    }
}

Output

---- Traversing the set-----
Value -  Chennai
Value -  Hyderabad
Value -  Mumbai
Value -  New Delhi

Navigable methods

As already mentioned ConcurrentSkipListSet in Java implements NavigableSet interface so it has many navigation methods returning the closest matches for given search targets. Let's see some of them in example code.

  • higher(E e) - Returns the least element in this set strictly greater than the given element, or null if there is no such element.
  • lower(E e) - Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
  • tailSet(E fromElement) - Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

public class CSSDemo {
    public static void main(String[] args) {
        NavigableSet<String> citySet = new ConcurrentSkipListSet<String>();
        citySet.add("New Delhi");
        citySet.add("Mumbai");
        citySet.add("Chennai");
        citySet.add("Hyderabad");
        
        System.out.println("---- Traversing the set-----");
        Iterator<String> itr = citySet.iterator();
        while(itr.hasNext()){
            System.out.println("Value -  " + itr.next());
        }
        
        System.out.println("Higher - " + citySet.higher("C"));
        
        System.out.println("Lower - " + citySet.lower("Mumbai"));
        
        System.out.println("---- Tail Set -----");
        
        Set<String> set = citySet.tailSet("Hyderabad");
        
        itr = set.iterator();
        while(itr.hasNext()){
            System.out.println("Value -  " + itr.next());
        }
    }
}

Output

---- Traversing the set-----
Value -  Chennai
Value -  Hyderabad
Value -  Mumbai
Value -  New Delhi
Higher - Chennai
Lower - Hyderabad
---- Tail Set -----
Value -  Hyderabad
Value -  Mumbai
Value -  New Delhi

Here higher as the description says is returning the least element in this set strictly greater than the given element. Since given element is "C" so returned value is "Chennai". Note that passed element doesn't have to be the one already present in set as here "C" is passed which is not an element of the Set.

lower as the description says is returning the greatest element in this set strictly less than the given element. Passed element is "Mumbai" so that returned element is "Hyderabad".

That's all for this topic ConcurrentSkipListSet in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ConcurrentHashMap in Java
  2. CopyOnWriteArraySet in Java
  3. ArrayBlockingQueue in Java Concurrency
  4. CountDownLatch in Java concurrency
  5. Java Concurrency Interview Questions

You may also like -

How to Convert Date to String in Java

In most of the Java application it’s a very common requirement to print date in a required format. For that you do need to convert date to a String that is in the required format. In this post we’ll see options to convert date to String in Java.

Using SimpleDateFormat

A tried and tested way to convert date to string in Java is to use SimpleDateFormat which also gives you an option to provide customized format.

SimpleDateFormat resides in java.text package and extends DateFormat class which is an abstract class. DateFormat class also provides predefined styles to format dates and times.

Here note that SimpleDateFormat is not thread safe so not safe to use in multi-threaded application with out proper synchronization. An alternative way is to use ThreadLocal class, see an example of how ThreadLocal can be used by storing separate instance of SimpleDateFormat for each thread here.

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time.

Example code

Let’s see an example to convert date to String using the given format.

In this example there is a method getFormattedDate() where pattern is passed as an argument. Date is converted to String using the passed pattern.

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {

 public static void main(String[] args) {
  FormatDate fd = new FormatDate();
  
  // For date in format Wed, Jun 8, '16
  fd.getFormattedDate("EEE, MMM d, ''yy");

  // For date in format Wednesday, June 08, 2016
  fd.getFormattedDate("EEEE, MMMM dd, yyyy");

  // For date in format 05/08/2016
  fd.getFormattedDate("MM/dd/yyyy");

  // For date in format 08/05/2016
  fd.getFormattedDate("dd/MM/yyyy");
  
  // Only time like 21:52:14:096 PM
  // in 24 hr format, with mili seconds and AM/PM marker
  fd.getFormattedDate("HH:mm:ss:SSS a");

 }
 
 /**
  * 
  * @param pattern
  */
 public void getFormattedDate(String pattern){
  Date today;
  String result;
  SimpleDateFormat formatter;
  // Creating the date format using the given pattern
  formatter = new SimpleDateFormat(pattern);
  // Getting the date instance
  today = new Date();
  // formatting the date
  result = formatter.format(today);
  System.out.println("Pattern: " + pattern + 
    " Formatted Date - " + result);
 }

}

Output

Pattern: EEE, MMM d, ''yy Formatted Date - Sun, Aug 13, '17
Pattern: EEEE, MMMM dd, yyyy Formatted Date - Sunday, August 13, 2017
Pattern: MM/dd/yyyy Formatted Date - 08/13/2017
Pattern: dd/MM/yyyy Formatted Date - 13/08/2017
Pattern: HH:mm:ss:SSS a Formatted Date - 12:50:14:097 PM

Using DateFormatter of new Java Date & Time API – Java 8

From Java 8 there is another option to convert date to a string in required format. If you have an object of type LocalDate, LocalTime or LocalDateTime you can format it using the DateFormatter class. All these classes reside in java.time package.

All these classes LocalDate, LocalTime or LocalDateTime have format method that takes object of DateFormatter class as argument. Using that object of DateFormatter format for conversion can be provided.

You can use static methods ofLocalizedDate(FormatStyle dateStyle), ofLocalizedTime(FormatStyle dateStyle) or ofLocalizedDateTime(FormatStyle dateStyle) based on the type of object you are using to provide the pattern for formatting. Here FormatStyle is an Enumeration with the following Enum constants. Note that these methods return a locale specific date-time formatter.
  • public static final FormatStyle FULL - Full text style, with the most detail. For example, the format might be 'Tuesday, April 12, 1952 AD' or '3:30:42pm PST'.
  • public static final FormatStyle LONG - Long text style, with lots of detail. For example, the format might be 'January 12, 1952'.
  • public static final FormatStyle MEDIUM - Medium text style, with some detail. For example, the format might ' be 'Jan 12, 1952'.
  • public static final FormatStyle SHORT - Short text style, typically numeric. For example, the format might be '12.13.52' or '3:30pm'.

DateFormatter Java Example Code

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  String strDate =  getFormattedDate(curDateTime);
  System.out.println("Formatted date - " + strDate); 
 }
 
 private static String getFormattedDate(LocalDateTime dt){
  DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
  return dt.format(df1);
 }

}

Output for FULL

Date before formatting 2017-08-13T20:08:25.056
Formatted date - Sunday, 13 August, 2017

Output for LONG

Date before formatting 2017-08-13T20:08:54.921
Formatted date - 13 August, 2017

Output for MEDIUM

Date before formatting 2017-08-13T20:09:27.308
Formatted date - 13 Aug, 2017

Output for SHORT

Date before formatting 2017-08-13T20:09:53.465
Formatted date – 13/8/17

Using ofPattern() method

You can also use ofPattern() method to provide the pattern for formatting. Using this method you can provide custom format.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  // Passing custom pattern
  getFormattedDate(curDateTime, "dd/MM/yyyy");
  //String strDate =  getFormattedDate(curDateTime);
  //System.out.println("Formatted date - " + strDate);
  
  getFormattedDate(curDateTime, "YYYY MMM dd");
  
  getFormattedDate(curDateTime, "MMMM dd yyyy hh:mm a");
 }

 
 /**
  * 
  * @param dt
  * @param pattern
  * @return
  */
 private static void getFormattedDate(LocalDateTime dt, String pattern){
  DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
  System.out.println("Formatted date " + " For Pattern " + pattern + " is "+ dt.format(df));
 }

}

Output

Date before formatting 2017-08-13T20:20:07.979
Formatted date  For Pattern dd/MM/yyyy is 13/08/2017
Formatted date  For Pattern YYYY MMM dd is 2017 Aug 13
Formatted date  For Pattern MMMM dd yyyy hh:mm a is August 13 2017 08:20 PM

That's all for this topic How to convert Date to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to convert String to Date in Java
  2. How to convert date and time between different time-zones in Java
  3. How to format date in Java using SimpleDateFormat
  4. How to Format Time in AM-PM Format - Java Program
  5. How to find last modified date of a file in Java

You may also like -

>>>Go to Java Programs Page

Generating Getters And Setters Using Reflection - Java Program

When you right click in any Java Bean class with in the eclipse IDE and click on Source – Generate Getters and Setters you get the getter and setter methods for the selected fields. Ever wondered what goes in the background to generate the getter and setter methods?

Yes, it is the magic of reflection in Java which gets the information about the fields of the class and their types and then generate the getters and setters using reflection accordingly.

If you have to create such a class yourself then using the refelction API you can create your own getters and setters generator class, of course just for academic purpose, as all the IDEs anyway provide the facility to do that.

Example code

Let’s say you have a class TestClass with three fields of type int, String and Boolean and you want to generate getters and setters for these 3 fields.

TestClass

public class TestClass {

 private int value;
 private String name;
 private boolean flag;
} 

GetterSetterGenerator class

Using the reflection API for the field you can get information about the fields of the given class – like name and type. Once you have that information you can create set and get methods for the fields. In this code set and get methods are just printed after creating them as it is just for illustrating the usage of reflection in Java so not going into File I/O.

import java.lang.reflect.Field;
import java.util.Arrays;

public class GetterSetterGenerator {

 public static void main(String[] args) {
  try {
   GetterSetterGenerator gt = new GetterSetterGenerator();
   StringBuffer sb = new StringBuffer();
   
   Class<?> c = Class.forName("org.prgm.TestClass");
   // Getting fields of the class
   Field[] fields = c.getDeclaredFields();
   System.out.println("Fields - " + Arrays.toString(fields));
   for(Field f : fields){
    String fieldName = f.getName();
    String fieldType = f.getType().getSimpleName();
    
    System.out.println("Field Name -- " + fieldName);
    System.out.println("Field Type " + fieldType);
    
    gt.createSetter(fieldName, fieldType, sb);
    
    gt.createGetter(fieldName, fieldType, sb);
   }
   System.out.println("" + sb.toString());
   
  }catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  


 }
 /**
  * 
  * @param fieldName
  * @param fieldType
  * @param setter
  */
 private void createSetter(String fieldName, String fieldType, StringBuffer setter){
  
  setter.append("public void").append(" set");
  setter.append(getFieldName(fieldName));
  setter.append("(" + fieldType + " " + fieldName + ") {");
  setter.append("\n\t this."+ fieldName + " = " + fieldName + ";");
  setter.append("\n" + "}" + "\n");
 }
 
 /**
  * 
  * @param fieldName
  * @param fieldType
  * @param setter
  */
 private void createGetter(String fieldName, String fieldType, StringBuffer getter){
  getter.append("public " + fieldType).append((fieldType.equals("boolean")?" 
    is" : " get") + getFieldName(fieldName) + "(){");
  getter.append("\n\treturn " + fieldName + ";");
  getter.append("\n" + "}" + "\n");
 }
 
 /**
  * 
  * @param fieldName
  * @return
  */
 private String getFieldName(String fieldName){
  return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(
    1, fieldName.length());
 }
}

Output

 Fields - [private int org.prgm.TestClass.value, private java.lang.String org.prgm.TestClass.name, private boolean org.prgm.TestClass.flag]
Field Name -- value
Field Type int
Field Name -- name
Field Type String
Field Name -- flag
Field Type Boolean

public void setValue(int value) {
  this.value = value;
}
public int getValue(){
 return value;
}
public void setName(String name) {
  this.name = name;
}
public String getName(){
 return name;
}
public void setFlag(boolean flag) {
  this.flag = flag;
}
public boolean isFlag(){
 return flag;
}

That's all for this topic Generating Getters And Setters Using Reflection - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Invoking getters and setters using Reflection - Java Program
  2. Reflection in Java - Class
  3. Reflection in Java - Method
  4. Reflection in Java - Constructor
  5. Reflection in Java

You may also like -

>>>Go to Java Advance Topics Page

Invoking Getters And Setters Using Reflection - Java Program

In the post reflection in java – method it is already explained how you can invoke a method of the class at runtime even a private method.

In this post we’ll use that knowledge to invoke getters and setters of the class using reflection. In Java you can do it using two ways, here both of them are discussed-

  • Using the PropertyDescriptor class.
  • Scanning methods of the class and look for set and get methods.

Using PropertyDescriptor class

A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods. Then using the getReadMethod() and getWriteMethod() you can call the setter and getter for the property.

Example Code

Here in the example we have a class TestClass which has getter and setter for three fields which are of type int, String and boolean. Then in the GetterAndSetter class there are methods to invoke the getters and setters of the given class.

TestClass.java

package org.prgm;

public class TestClass {
 private int value;
 private String name;
 private boolean flag;
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public boolean isFlag() {
  return flag;
 }
 public void setFlag(boolean flag) {
  this.flag = flag;
 }
}

GetterAndSetter.java

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class GetterAndSetter {
 public static void main(String[] args) {
  GetterAndSetter gs = new GetterAndSetter();
  TestClass tc = new TestClass();
  gs.callSetter(tc, "name", "John");
  gs.callSetter(tc, "value", 12);
  gs.callSetter(tc, "flag", true);
  // Getting fields of the class
  Field[] fields = tc.getClass().getDeclaredFields();
  
  for(Field f : fields){
   String fieldName = f.getName();
   System.out.println("Field Name -- " + fieldName);
  }
  gs.callGetter(tc, "name");
  gs.callGetter(tc, "value");
  gs.callGetter(tc, "flag");
 }
 
 /**
  * 
  * @param obj
  * @param fieldName
  * @param value
  */
 private void callSetter(Object obj, String fieldName, Object value){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   pd.getWriteMethod().invoke(obj, value);
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 /**
  * 
  * @param obj
  * @param fieldName
  * @param value
  */
 private void callGetter(Object obj, String fieldName){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   System.out.println("" + pd.getReadMethod().invoke(obj));
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Field Name -- value
Field Name -- name
Field Name -- flag
John
12
true

Scanning methods of the class and look for set and get methods

Another way to invoke the getters and setters using Java reflection is to scan all the methods of the class through reflection and then find out which are the getters and setters method.

It is particularly useful to use this way to call get methods if you have lots of fields in a class. Calling set method that way won’t be of much help as you will have to still invoke individual method with the value that has to be set.

Logic to identify get method

get method starts with get or is (in case of boolean), it should not have any parameters and it should return a value.

Logic to identify set method

set method starts with set and it should have a parameter and it shouldn't return any value which means it should return void.

Example Code

Same Java bean class as above TestClass is used here too.

GetterAndSetter.java

In the GetterAndSetter class there are methods to identify the getters and setters of the given class. If it is a get method that is invoked to get the value. For set method name of the method is printed.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GetterAndSetter {
    public static void main(String[] args) {
        TestClass tc = new TestClass();
        // Setting values
        tc.setName("John");
        tc.setValue(12);
        tc.setFlag(true);
        
        Method[] methods = tc.getClass().getDeclaredMethods();
        for(Method method : methods){
            if(isGetter(method)){
                try {
                    Object obj = method.invoke(tc);
                    System.out.println("Invoking "+ method.getName() + " 
                     Returned Value - " + obj);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(isSetter(method)){
                System.out.println("Setter -- " + method.getName());
            }
        }
    }
    
    /**
     * 
     * @param method
     * @return
     */
    private static boolean isGetter(Method method){
        // identify get methods
        if((method.getName().startsWith("get") || method.getName().startsWith("is")) 
          && method.getParameterCount() == 0 && !method.getReturnType().equals(void.class)){
            return true;
        }
        return false;    
    }
    
    /**
     * 
     * @param method
     * @return
     */
    private static boolean isSetter(Method method){
        // identify set methods
        if(method.getName().startsWith("set") && method.getParameterCount() == 1 
          && method.getReturnType().equals(void.class)){
            return true;
        }
        return false;    
    }
}

Output

Invoking getName Returned Value - John
Invoking getValue Returned Value - 12
Setter -- setName
Setter -- setValue
Setter -- setFlag
Invoking isFlag Returned Value - true

That's all for this topic Invoking Getters And Setters Using Reflection - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Generating getters and setters using Reflection - Java Program
  2. Reflection in Java
  3. Reflection in Java - Class
  4. Reflection in Java - Constructor
  5. Reflection in Java - Field

You may also like -

>>>Go to Java Advance Topics Page

How to Sort an ArrayList in Descending Order in Java

When you add elements to an ArrayList, elements are added in sequential order and while iterating an arraylist same sequential order will be used to retrieve the elements.

Sometimes we do have a requirement to sort an arraylist in ascending or descending order. In this post we'll see how to sort an ArrayList in descending order.

Sorting ArrayList in descending order

For sorting ArrayList in descending order in Java there are two options

  1. Use method reverseOrder() provided by Collections class.
  2. General form and description

    public static <T> Comparator<T> reverseOrder()
    
    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
  3. Using a custom comparator.

If you are using the first option then you must also know about the overloaded method sort provided by the Collections class.

  • public static <T> void sort(List<T> list, Comparator<? super T> c) - Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).

reverseOrder() method mentioned above can be provided as the second parameter in the sort method mentioned above and you will get the ArrayList sorted in reverse order. Let's see an example-

Sorting ArrayList Using reverseOrder method

public class SortListDemo {

    public static void main(String[] args) {
        // Using diamond operator (Right side no type specified)
        // Available from Java7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Chennai");
        cityList.add("Kolkata");
        cityList.add("Mumbai");
        // sorting the list in descending order
        Collections.sort(cityList, Collections.reverseOrder());
        //Displaying the list
        for(String city : cityList){
            System.out.println("Name " + city);
        }
    }
}

Output

Name Mumbai
Name Mumbai
Name Kolkata
Name Delhi
Name Chennai
Name Bangalore

Sorting ArrayList Using custom Comparator

Internally reverseOrder method calls a Comparator class to do the sorting in reverse order. You can do it yourself too by writing your own comparator class.

public class SortListDemo {
    public static void main(String[] args) {
        // Using diamond operator (Right side no type specified)
        // Available from Java7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Chennai");
        cityList.add("Kolkata");
        cityList.add("Mumbai");
        // sorting the list in descending order
        Collections.sort(cityList, new MyComparator());
        //Displaying the list
        for(String city : cityList){
            System.out.println("Name " + city);
        }
    }
}


//Custom comparator class
class MyComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }    
}

Comparator with Java 8

Since Comparator is a functional interface so we can use lambda expression to provide implementation of its abstract method. That will reduce the custom comparator implementation to a single line. Don't forget to import the comparator interface though.

Example code

public class SortListDemo {
    public static void main(String[] args) {
        // Using diamond operator (Right side no type specified)
        // Available from Java7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Chennai");
        cityList.add("Kolkata");
        cityList.add("Mumbai");
        // sorting the list in descending order
        Collections.sort(cityList, (String a, String b)->  b.compareTo(a));
        //Displaying the list
        for(String city : cityList){
            System.out.println("Name " + city);
        }
    }
}

Output

Name Mumbai
Name Mumbai
Name Kolkata
Name Delhi
Name Chennai
Name Bangalore

Sorting ArrayList of custom objects

Let's say there is an Employee class with fields EmpId, FirstName, LastName and Age and you want to sort elements as per following rules.

  • Sort on FirstName in ascending order.
  • If FirstName is same then sort on LastName in ascending order.
  • If both FirstName and LastName are same the sort on Age in Descending order.

Employee Class

public class Employee {
    private String lastName;
    private String firstName;
    private String empId;
    private int age;
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        
        return getFirstName() + " " + getLastName() + " " + getAge() + " " + getEmpId();
    }
}

Sorting logic

public class SortObjList {

    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<Employee>();
        // Storing elements in the arraylist
        empList.add(getData("E001", "Mishra", "Ram", 30));
        empList.add(getData("E002", "Smith", "John", 45));
        empList.add(getData("E003", "Smith", "John", 23));
        empList.add(getData("E004", "Mishra", "Pyaremohan", 60));
        empList.add(getData("E005", "Caroll", "Eva", 32));
        empList.add(getData("E003", "Tiwari", "Ram", 35));
            
        System.out.println("Original List");
        for(Employee emp : empList){
            System.out.println("" + emp);
        }
        // Sorting the list
        Collections.sort(empList, new MyComparator());
                
        System.out.println("Sorted List");
        for(Employee emp : empList){
            System.out.println("" + emp);
        }    
    }
                    
    // Stub method
    private static Employee getData(String empId, String lastName, 
          String firstName, int age){
        Employee employee = new Employee();
        employee.setEmpId(empId);
        employee.setLastName(lastName);
        employee.setFirstName(firstName);
        employee.setAge(age);
        return employee;
    }
}

class MyComparator implements Comparator<Employee>{
    @Override
    public int compare(Employee o1, Employee o2) {
        int firstCmp = o1.getFirstName().compareTo(o2.getFirstName());
        if(firstCmp == 0){
            int lastCmp = o1.getLastName().compareTo(o2.getLastName());
            if(lastCmp == 0){
                return (o2.getAge() < o1.getAge() ? -1 :
                       (o2.getAge() == o1.getAge() ? 0 : 1));
            }else{
                return lastCmp;
            }
            
        }else{
            return firstCmp;
        }        
    }    
}

Output

Original List
Ram Mishra 30 E001
John Smith 45 E002
John Smith 23 E003
Pyaremohan Mishra 60 E004
Eva Caroll 32 E005
Ram Tiwari 35 E003

Sorted List
Eva Caroll 32 E005
John Smith 45 E002
John Smith 23 E003
Pyaremohan Mishra 60 E004
Ram Mishra 30 E001
Ram Tiwari 35 E003

Here it can be seen that Employees are sorted on the basis of first name in ascending order. There are two John Smiths so in that case sorting is done on the basis of age in descending order. And For Ram Tiwari and Ram Mishra since first name is same so sorting is done on the basis of last name in ascending order.

That's all for this topic How to Sort an ArrayList in Descending Order in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Sort ArrayList of Custom Objects in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. How LinkedList Class Works Internally in Java
  5. CopyOnWriteArrayList in Java - The thread safe variant of ArrayList

You may also like -

Saturday, 30 December 2017

LinkedHashSet in Java

LinkedHashSet is also one of the implementation of the Set interface in Java. Actually LinkedHashSet class in Java extends the HashSet and has no other methods of its own.

Just like other implementations of the Set interface HashSet and TreeSet, LinkedHashSet also stores unique elements. How LinkedHashSet differs from the HashSet in Java is that it maintains the insertion-order; that is elements in the LinkedHashSet are stored in the sequence in which they are inserted. Note that insertion order is not affected if an element is re-inserted into the set.

How LinkedHashSet is implemented in Java

LinkedHashSet is the Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. If you have idea about how HashSet works internally in Java, you must be knowing internally HashSet uses HashMap for storing its elements.

In case of LinkedHashSet it will call the methods of HashSet class for all the operations, but it will use LinkedHashMap internally.

Just take any of the Constructor of the LinkedHashSet and you will see all those contructors will ultimatey call the Constructor of the HashSet where map will be initialized as a LinkedHashMap.

LinkedHashSet Java example code

public class LinkedHSDemo {

    public static void main(String[] args) {
        // Using Diamond operator Which is available from Java 7
        // Use LinkedHashSet<String> if using less than version 7
        Set<String> citySet = new LinkedHashSet<>();
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add(null);
        citySet.add("Bangalore");
        citySet.add("Delhi");
        citySet.add(null);
        
        // Iterating the Set
        for(String str : citySet){
            System.out.println("" + str);
        }     
    }
}

Output

Delhi
Mumbai
null
Bangalore

Points to note here -

  • It can be seen that the insertion order is maintained. While iterating the LinkedHashSet elements are displayed in the order they were inserted.
  • Even though Delhi is inserted twice it is displayed only once which shows that the insertion order is not affected if an element is re-inserted into the set.
  • Only one null is allowed in the LinkedHashSet, even if I have tried to insert null twice it can be seen that only one is stored.

LinkedHashSet is not synchronized

LinkedHashSet in Java is not thread safe. In case we need to Synchronize it, it should be synchronized externally. That can be done using the Collections.synchronizedSet method.

Set s = Collections.synchronizedSet(new LinkedHashSet(...));

LinkedHashSet class's iterator is fail-fast

Iterator returned by LinkedHashSet is fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

Performance of LinkedHashSet in Java

The performance of LinkedHashSet is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list. But there is one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity as in the case of HashSet based on the Hashing function it may have to go through all the buckets .

That's all for this topic LinkedHashSet in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashSet Works Internally in Java
  2. TreeSet in Java
  3. EnumSet in Java
  4. How to Sort Elements in Different Order in TreeSet
  5. Java Collections Interview Questions

You may also like -