Monday, 26 October 2015

How to find last modified date of a file - Java Program

In Java, there are two ways to get the last modified date of the file. If you are using version of Java less than 7 then you can use the File.lastModified() method to get the file's last modified timestamp.

If you are using Java 7 or above then you can also use java.nio BasicFileAttributes to get all the attributes associated with the file. That way apart from last modified date you can also get the file creation date and several other attributes.

public class FileDate {
    public static void main(String[] args) {
        /*For below Java 7*/ 
        // get the file
        File f = new File("F:\\NetJS\\programs.txt");
        // Create a date format
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        // get the last modified date and format it to the defined format
        System.out.println("File last modified date " + sdf.format(f.lastModified()));
        
        /*Java 7 or above using NIO*/
        // Get the file
        Path path = Paths.get("F:\\NetJS\\programs.txt");
        BasicFileAttributes attr;
        try {
            // read file's attribute as a bulk operation
            attr = Files.readAttributes(path, BasicFileAttributes.class);
            // File creation time
            System.out.println("File creation time - " + sdf.format(attr.creationTime().toMillis()));
            // File last modified date
            System.out.println("File modified time - " + sdf.format(attr.lastModifiedTime().toMillis()));
            
        } catch (IOException e ) {
            System.out.println("Error while reading file attributes " + e.getMessage());
        }
        
    }
}

Note here that when java.io.File lastModified method is used it returns the time in milliseconds (long) so SimpleDateFormat is used to format it into dd/MM/yyyy format.
Same way in the java.nio when attributes of the file are read, both file creation date and last modified date are displayed. Again the returned date is converted to milliseconds and then formatted to the desired format.

That's all for this topic How to find last modified date of a file. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to format date in Java using SimpleDateFormat
  2. How to read file from the last line in Java
  3. How to read input from console in Java?
  4. Reading file in Java using Scanner
  5. Reading file in Java using BufferedReader

You may also like -

>>>Go to Java Programs page

Friday, 23 October 2015

How to Sort elements in different order in TreeSet - Java Program

By default elements are stored in TreeSet using natural ordering. If you want to sort using different order then you need to provide your own comparator at set creation time. Let's see an example where we sort the Strings in descending order rather than the natural ordering (which is ascending in case of String).

  public class TreeSetDemo {
    public static void main(String[] args) {
        // Providing custom compartor
        Set<String> citySet = new TreeSet<String>(new CityComparator());
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add("Bangalore");
        citySet.add("Chennai");
        citySet.add("Hyderabad");
        
        // Iterating the Set
        for(String str : citySet){
            System.out.println("City Name - " + str);
        }
    }
}

// Comparator class
class CityComparator implements Comparator<String>{
    @Override
    public int compare(String str1, String str2) {
        return str2.compareTo(str1);
    }    
}

Output

City Name - Mumbai
City Name - Hyderabad
City Name - Delhi
City Name - Chennai
City Name - Bangalore

Here note that a comparator is provided which reverses the sorting order. That comparator is provided at the set creation time in a constructor.

That's all for this topic How to sort elements in different order in TreeSet. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference between Comparable and Comparator
  2. LinkedHashSet in Java
  3. TreeSet in Java
  4. How to sort arraylist in Java
  5. How to sort arraylist of custom objects in Java
  6. Count total number of times each character appears in a String

You may also like -

>>>Go to Java Programs page

Wednesday, 21 October 2015

Difference between Comparable and Comparator

While sorting elements in collection comparable and comparator interfaces come into picture which are used to sort collection elements. A natural question which comes to mind is why two different interfaces?

So in this post I'll try to explain the difference between comparable and comparator interfaces and why both of them are required. Before going into the differences between these two, let's have a brief introduction of both.

  • Comparable interface: Class whose objects are to be sorted implements this interface. The ordering imposed by the implementation of this interface is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. Classes implementing this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map (like TreeMap) or as elements in a sorted set (like TreeSet), without the need to specify a comparator.

    General form of Comparable interface -

    public interface Comparable<T> {
     public int compareTo(T o);
    }
    
  • Comparator interface: In the case of Comparator, class that is to be sorted doesn't implement it. Comparator can be implemented by some other class, as an anonymous class or as lambda expression (from Java 8). Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps).

    General form of Comparator interface -

    @FunctionalInterface
    public interface Comparator<T> {
      int compare(T o1, T o2);
    }
    

Note the annotation @FunctionalInterface, it's available from Java 8 and Comparator being a functional interface can be implemented using lambda expression.

Also note that apart from compare method which is the single abstract method there are several other default and static methods too with in the Comparator interface.

Java Example code

Let's see an example to further clarify when do we need comparable and when Comparator is needed.

Let's say we have an Employee class. Objects of this Employee class are stored in an array list and we want to sort it first on first name and then on last name. So this order is the natural order for the Employee class, employees are first sorted on first name and then last name.

Employee class

public class Employee implements Comparable<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();
    }
    @Override
    public int compareTo(Employee o) {
        int firstCmp = this.getFirstName().compareTo(o.getFirstName());
        return firstCmp != 0 ? firstCmp :  this.getLastName().compareTo(o.getLastName());
    }
}

Here note that Employee class is implementing Comparable interface providing implementation for the compareTo() method.

Class where sorting of the list will be done

public class SortObjectList {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<Employee>();
        // Storing elements in the arraylist
        empList.add(getData("E001", "Mishra", "Pyaremohan", 35));
        empList.add(getData("E002", "Smith", "John", 45));
        empList.add(getData("E003", "Sharma", "Ram", 23));
        empList.add(getData("E004", "Mishra", "Pyaremohan", 60));
        empList.add(getData("E005", "Caroll", "Eva", 32));
        empList.add(getData("E003", "Tiwari", "Ram", 23));
        
        System.out.println("Original List");
        for(Employee emp : empList){
            System.out.println("" + emp);
        }
        // Sorting the list
        Collections.sort(empList);
        
        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;
    }    
}

Output

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

When do we need Comparator

Now in case we want to sort in an order where, if names are same, they are sorted on the basis of age in descending order we can't use the already implemented compareTo() method of the Employee class. So you can say that if we want any ordering other than the defined natural ordering for the class then we have to use Comparator. In that case Comparator will provide an object that encapsulates an ordering.

Sorting logic

public class SortObjectList {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<Employee>();
        // Storing elements in the arraylist
        empList.add(getData("E001", "Mishra", "Pyaremohan", 35));
        empList.add(getData("E002", "Smith", "John", 45));
        empList.add(getData("E003", "Sharma", "Ram", 23));
        empList.add(getData("E004", "Mishra", "Pyaremohan", 60));
        empList.add(getData("E005", "Caroll", "Eva", 32));
        empList.add(getData("E003", "Tiwari", "Ram", 23));
        
        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
Pyaremohan Mishra 35 E001
John Smith 45 E002
Ram Sharma 23 E003
Pyaremohan Mishra 60 E004
Eva Caroll 32 E005
Ram Tiwari 23 E003
Sorted List
Eva Caroll 32 E005
John Smith 45 E002
Pyaremohan Mishra 60 E004
Pyaremohan Mishra 35 E001
Ram Sharma 23 E003
Ram Tiwari 23 E003

Here it can be seen that the name which is same is sorted by age in descending order.
Note here that a Comparator class MyComparator is implementing the Comparator interface and providing implementation for the compare() method. Also note that in Collections.sort method now we need to provide the Comparator class.

Collections.sort(empList, new MyComparator());

Comparator class can also be implemented as an Anonymous class or as a Lambda expression.

I hope now it is clear why two interfaces are provided for sorting and how they are used. So let's see the difference now -

Comparable Comparator
Comparable interface is in java.lang package. Comparator interface is in java.util package.
Comparable interface provides public int compareTo(T o); method which needs to be implemented for sorting the elements.
This method compares this object with object o and returns an integer, if that integer is -
  • Positive - this object is greater than o.
  • Zero - this object is equal to o.
  • Negative - this object is less than o.
Comparator interface provides int compare(T o1, T o2); method which needs to be implemented for sorting the elements. Here o1 and o2 objects are compared and an integer value is returned, if that integer is -
  • Positive - o1 is greater than o2.
  • Zero - o1 is equal to o2.
  • Negative - o1 is less than o2.
The class which has to be sorted should implement the comparable interface (sorting logic is in the class which has to be sorted), and that implementation becomes the natural ordering of the class. Some other class can implement the Comparator interface not the actual class whose objects are to be sorted. That way there may be many comparators and depending on the ordering needed specific comparator can be used. As example for Employee class if different orderings are needed based on first name, last name, age etc. then we can have different comparators with the implementations for those orderings.
To sort the list when Comparable is used we can use Collections.sort(List). To sort the list when Comparator is used, Comparator class has to be explicitly specified as a param in the sort method. Collections.sort(List, Comparator)

That's all for this topic Difference between comparable and comparator. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. How to sort arraylist in Java
  2. How to sort arraylist of custom objects in Java
  3. How to sort an ArrayList in descending order
  4. How to Sort elements in different order in TreeSet using Comparator
  5. Java Collections interview questions

You may also like -

Monday, 19 October 2015

Spring example program using automatic configuration

Though there are ways to explicitly wire dependencies by using Spring XML configuration or Spring JavaConfig but Spring also provides automatic configuration. Two things you need to know for automatic configuration are -

  • Component scanning- Spring does the work of automatically discovering the beans to be created in the application context rather than you explicitly defining them. It is done using the annotation @Component (and some other variants of it like @Service, @Repository, @Controller or any custom annotation that itself is annotated with @Component).
  • Autowiring- Spring does the work of automatically detecting and wiring the dependencies.

In this tutorial Maven is used to create a general Java project structure.

Technologies used

  • Spring 4.2.1
  • JDK 1.8
  • Apache Maven 3.3.3
  • Eclipse Luna 4.2.2

 In this Spring program there are 2 classes; first is Payment Service and another is Cash Payment class, let's go step by step to see how these classes are created and configured using Spring automatic configuration.

  1. Provide dependencies in pom.xml of Maven

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>org.netjs.prog</groupId>
      <artifactId>maven-spring</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>maven-spring</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.1.RELEASE</spring.version>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
      </dependencies>
    </project>
    

    Note that you'll already have most of the entries in pom.xml, you just need to add dependencies for spring-core and spring-context and an entry for spring.version in properties element. Spring-context is needed for the annotations.

  2. Create Java classes

    We need 2 classes PaymentService and CashPayment. Since Spring promotes loose coupling so it is always recommended to code to interfaces. So we'll also create interfaces for the classes.

    Payment Service

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

    Here note that the class is annotated with @Service annotation, that's how it is made sure that this class is discovered while a component scan is done. Also note that the dependency to the payment is annotated with the annotation @Autowired. That's how Spring will automatically detect this dependency and inject it.

    Cash Payment

    public interface IPayment {
     void executePayment();
    }
    
    @Component
    public class CashPayment implements IPayment{
     public void executePayment() {
      System.out.println("Perform Cash Payment - ");
      
     }
    }
    
  3. Confguration class

    For automatic configuration we can use either a Java class or XML configuration. I'll show both the way here.

    If you are using XML configuration then you need to use context:component-scan with base-package. I have created Java classes in the package org.netjs.prog so that's what I'll give as the base package.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
     
     <context:component-scan base-package="org.netjs.prog" />
    </beans>
    

    Notice the addition of new name space.

    xmlns:context="http://www.springframework.org/schema/context"
    

    This is required because we are using context:component-scan.

    If you are using Java class then you just need this

    @Configuration
    @ComponentScan(basePackages="org.netjs.prog")
    public class AppConfig {
        
    }
    

    You can annotate a Java class with @ComponentScan and provide the package which is to be scanned with basePackage attribute. You don't need to provide any code with in the class.

  4. Java class to run the application

    If you are using XML configuration then the Java class to run the application will be like this -

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

    Here appcontext.xml is the name of the XML file created above.

    If you are using Java class then the class to run the application will be like this -

    public class App {
        public static void main( String[] args ){  
            AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
            IPayService bean = (IPayService) context.getBean("payServiceImpl");
            bean.performPayment();
            context.close();
        }
    }
    

    Here note that AnnotationConfigApplicationContext is used to create the Spring application context which takes the JavaConfig class as input.

No Unique bean definition Exception

In the above application we had used only one implementation of IPayment, CashPayment so there was no problem in automatically wiring it. Now suppose we have one more implementation of the IPayment interface, Credit Payment. In that case with the current setup you'll get NoUniqueBeanDefinitionException because Spring won't know which Payment class to wire.

For these types of scenarios where ambiguity is there Spring provides couple of options. One of them is using @Qualifier annotation to qualify the bean.

Code for CreditPayment class

@Component
public class CreditPayment implements IPayment {
 public void executePayment() {
  System.out.println("Performing credit payment ");

 }

}

Since we have two classes now, implementing IPayment interface so we need to make changes in the PayServiceImpl class and use the qualifier annotation to wire the dependency. If we need CreditPayment class to be wired then PayServiceImpl class will look like this.

@Service
public class PayServiceImpl implements IPayService {
    @Autowired
    @Qualifier("creditPayment")
    private IPayment payment;

    public void performPayment() {
        payment.executePayment();
    }
    
    public IPayment getPayment() {
        return payment;
    }

    public void setPayment(IPayment payment) {
        this.payment = payment;
    }
}

Note the Qualifier annotation used with the payment reference.

That's all for this topic Spring example program using automatic configuration. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring example program using XML configuration
  2. Spring example program using JavaConfig and Annotations
  3. What is Dependency Injection in Spring
  4. Autowiring using annotations in Spring
  5. Autodiscovery of bean using componenent-scan in Spring
  6. Different bean scopes in Spring

You may also like -

>>>Go to Spring tutorial page

Wednesday, 14 October 2015

EnumSet in Java

EnumSet in Java is a specialized set implementation for use with enum types. All of the elements stored in an enum set must, explicitly or implicitly, come from a single enum type that is specified while creating the set. EnumSet was introduced in Java 5 along with the Enum.

According to Java docs "Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set."

How EnumSet works

One of the things to note about EnumSet is that it is an abstract class and uses factory methods to create objects. There are two concrete implementations of EnumSet -

  • RegularEnumSet
  • JumboEnumSet
Any of these two classes can't be instantiated directly by the user as these classes have default (package-private) access.

Depending upon the size of the Enum any of these classes is instantiated by the EnumSet class itself. If Enum has 64 or fewer enum constants then RegularEnumSet is used otherwise JumboEnumSet.

Example code using EnumSet

Since EnumSet can be used with an enum type so it provides use cases where some logic has to be used on the enum constants or EnumSet can be used instead of bit fields as explained in Effective Java.

Here I am creating an enum of weekdays and performing some logic to see whether it's a working day or not. Note how the EnumSet is created using the static factory methods of the EnumSet class and how methods provided by Set (for iteration, contains) are used for logic.

public class EnumSetDemo {
    // Enum
    private enum WeekDay {
         MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    }
    public static void main(String[] args) {
        // Creating EnumSet using range
        EnumSet<WeekDay> weekDaySet = EnumSet.range(
                    WeekDay.MONDAY, WeekDay.FRIDAY);
        // Creating EnumSet using complementOf method, The created 
        // set will contain all elements of the Enum not
        // contained in the specified set
        EnumSet<WeekDay> weekEndSet = EnumSet.complementOf(weekDaySet);
        
        //Another way of Creating EnumSet using of Method
        /*EnumSet<WeekDay> weekEndSet = EnumSet.of(
                    WeekDay.SATURDAY, WeekDay.SUNDAY);*/
        System.out.println("Using for each");
        // Iterating EnumSet
        for(WeekDay day : weekDaySet){
            System.out.println("Day - " + day);
        }
        
        System.out.println("Using itertor");
        Iterator<WeekDay> itr = weekEndSet.iterator();
        while(itr.hasNext()){
            System.out.println("Day - " + itr.next());
        }
        
        System.out.println("Need to work ? " + 
                    isWorkingDay(weekDaySet, WeekDay.MONDAY));
        System.out.println("Need to work ? " + 
                isWorkingDay(weekDaySet, WeekDay.SATURDAY));
    }
    private static boolean isWorkingDay(Set<WeekDay> daysSet, WeekDay day){    
        return daysSet.contains(day);
        
    }
}

Output

Using for each
Day - MONDAY
Day - TUESDAY
Day - WEDNESDAY
Day - THURSDAY
Day - FRIDAY
Using itertor
Day - SATURDAY
Day - SUNDAY
Need to work ? true
Need to work ? false

Nulls are not permitted

Null elements are not permitted in an EnumSet. Any attempt to insert a null element will throw NullPointerException.

Iteration of EnumSet

The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared). The returned iterator is weakly consistent: it will never throw ConcurrentModificationException and it may or may not show the effects of any modifications to the set that occur while the iteration is in progress. Note that example of Iteration using iterator is already there in the example code.

EnumSet is not synchronized

EnumSet is not synchronized. If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally. It can be done using the synchronizedSet method of the Collections class.
Collections.synchronizedSet(java.util.Set<T>)

That's all for this topic EnumSet 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. LinkedHashSet in Java
  3. TreeSet in Java
  4. How HashMap internally works in Java
  5. How ArrayList works internally in Java
  6. How Linked List class works internally in Java
  7. Java Collections interview questions

You may also like -

Tuesday, 13 October 2015

TreeSet in Java

TreeSet is also one of the implementation of the Set interface like HashSet and LinkedHashSet. TreeSet class implements the NavigableSet interface and extends the AbstractSet class.

Just like other implementations of the Set interface HashSet and LinkedHashSet, TreeSet also stores unique elements. How TreeSet differs from other implementations is that objects in TreeSet are stored in sorted order. The elements are ordered using their natural ordering or a comparator can be provided at set creation time to provide custom ordering (We'll see an example a little later).

How TreeSet is implemented

TreeSet uses a tree data structure to store its elements thus providing guaranteed log(n) time cost for the basic operations (add, remove and contains).

As we have seen while discussing HashSet and LinkedHashSet internally these implementations use their map counterparts i.e. HashMap and LinkedHashMap respectively. Same with TreeSet it also uses TreeMap internally to store its elements.

Example code using TreeSet

public class TreeSetDemo {

    public static void main(String[] args) {
        Set<String> citySet = new TreeSet<String>();
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add("Bangalore");
        citySet.add("Delhi");
        citySet.add("Chennai");
        citySet.add("Hyderabad");
        
        // Iterating the Set
        for(String str : citySet){
            System.out.println("City Name - " + str);
        }
        
        Set<Integer> numberSet = new TreeSet<Integer>();
        numberSet.add(6);
        numberSet.add(76);
        numberSet.add(1);
        numberSet.add(45);
        numberSet.add(89);
        numberSet.add(8);
        
        // Iterating the Set
        for(Integer num : numberSet){
            System.out.println("Number - " + num);
        }
    }
}

Output

City Name - Bangalore
City Name - Chennai
City Name - Delhi
City Name - Hyderabad
City Name - Mumbai
Number - 1
Number - 6
Number - 8
Number - 45
Number - 76
Number - 89

Here I have created 2 TreeSets, one stores Strings and another Integers. It can be seen that the TreeSet sorts the elements using their natural ordering which is ascending for both String and Integer. Also note that though Delhi is added twice but it is stored only once, so uniqueness is maintained.

Tree Set doesn't allow null

Though HashSet and LinkedHashSet allow one null, TreeSet doesn't allow null as element. Any attempt to add null in a TreeSet will result in a NullPointerException.

public class TreeSetDemo {

    public static void main(String[] args) {
        Set<String> citySet = new TreeSet<String>();
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add(null);
        citySet.add("Delhi");
        citySet.add("Chennai");
        citySet.add("Hyderabad");
        
        // Iterating the Set
        for(String str : citySet){
            System.out.println("City Name - " + str);
        }
    }
}

Output

Exception in thread "main" java.lang.NullPointerException
 at java.util.TreeMap.put(Unknown Source)
 at java.util.TreeSet.add(Unknown Source)
 at org.netjs.prog.TreeSetDemo.main(TreeSetDemo.java:14)

Sorting elements in different order in TreeSet

As already mentioned by default elements are stored in TreeSet using natural ordering. If you want to sort using different order then you need to provide your own comparator at set creation time. Let's see an example where we sort the Strings in descending order.

public class TreeSetDemo {

    public static void main(String[] args) {
        // Providing custom compartor
        Set<String> citySet = new TreeSet<String>(new CityComparator());
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add("Bangalore");
        citySet.add("Chennai");
        citySet.add("Hyderabad");
        
        // Iterating the Set
        for(String str : citySet){
            System.out.println("City Name - " + str);
        }
    }

}

// Comparator class
class CityComparator implements Comparator<String>{
    @Override
    public int compare(String str1, String str2) {
        return str2.compareTo(str1);
    }    
}

Output

City Name - Mumbai
City Name - Hyderabad
City Name - Delhi
City Name - Chennai
City Name - Bangalore

Here note that a comparator is provided which reverses the sorting order. That comparator is provided at the set creation time in a constructor.

TreeSet is not synchronized

TreeSet 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(...));

TreeSet class's iterator is fail-fast

The iterators returned by this class's iterator method are 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.

That's all for this topic TreeSet 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. LinkedHashSet in Java
  3. How ArrayList works internally in Java
  4. How HashMap internally works in Java
  5. Java Collections interview questions

You may also like -

Monday, 12 October 2015

Spring example program using XML configuration

In this post I'll talk about how to create a Spring example program using XML configuration. Though HelloWorld is a good starting point but better to go with an example which has at least two classes so that you can get idea about how those classes are defined in XML configuration and how dependencies are defined.
In this tutorial Maven is used to create a general Java project structure.

Technologies used

  • Spring 4.2.1
  • JDK 1.8
  • Apache Maven 3.3.3
  • Eclipse Luna 4.2.2

In this Spring program there are 2 classes; first is Payment Service and another is Cash Payment class, let's go step by step to see how these classes are configured in XML and how they are used.

  1. Provide dependencies in pom.xml of Maven

    <project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>org.netjs.exp</groupId>
      <artifactId>Spring-Example</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>Spring-Example</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.1.RELEASE</spring.version>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
      </dependencies>
    </project>
    

    Note that you'll already have most of the entries in pom.xml, you just need to add dependencies for spring-core and spring-context and an entry for spring.version in properties element.

  2. Create Java classes

    We need 2 classes PaymentService and CashPayment. Since Spring promotes loose coupling so it is always recommended to code to interfaces. So we'll also create interfaces for the classes.

    Payment Service

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

    Cash Payment

    public interface IPayment {
     void executePayment();
    }
    
    public class CashPayment implements IPayment{
     public void executePayment() {
      System.out.println("Perform Cash Payment "); 
     }
    }
    
  3. Spring XML Configuration

    Let's create a new source folder resources and save XML config there.
    To create source folder right click the Java project Spring-Example and select source folder.

    Spring example program using XML config

    In the next window provide the folder name and click finish.

    Spring example program using XML config

    Within the created folder create a XML file appcontext.xml and write the configuration for the beans in the created XML file.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        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.exp.Spring_Example.CashPayment" />
     
      <!-- Defining PayServiceImpl bean and injecting payment bean -->
      <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl">
          <property name="payment" ref="cashPaymentBean" />
      </bean>
    </beans>
    
  4. Java class to run the application

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

    Here we need to give the name of the XML configuration file. Then we can get the bean using the id provided in the XML config file.

Created project structure will look like this.

Spring example program using XML config

That's all for this topic Spring example program using XML configuration. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring example program using JavaConfig and Annotations
  2. Spring example program using automatic configuration
  3. Constructor-based dependency injection in Spring
  4. Different bean scopes in Spring
  5. Wiring collections in Spring
  6. Autowiring using XML configuration in Spring

You may also like -

>>>Go to Spring tutorial page

Spring example program using JavaConfig and Annotations

In this post I'll talk about how to create a Spring example program using JavaConfig. In this tutorial Maven is used to create a general Java project structure.

Technologies used

  • Spring 4.2.1
  • JDK 1.8
  • Apache Maven 3.3.3
  • Eclipse Luna 4.2.2

In this Spring program there are 2 classes; first is Payment Service and another is Cash Payment class, let's go step by step to see how these classes are created and configured using JavaConfig.

  1. Provide dependencies in pom.xml of Maven

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>org.netjs.exp</groupId>
      <artifactId>Spring-Example</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>Spring-Example</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.1.RELEASE</spring.version>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
      </dependencies>
    </project>
    

    Note that you'll already have most of the entries in pom.xml, you just need to add dependencies for spring-core and spring-context and an entry for spring.version in properties element. spring-context is needed for the annotations.

  2. Create Java classes

    We need 2 classes PaymentService and CashPayment. Since Spring promotes loose coupling so it is always recommended to code to interfaces. So we'll also create interfaces for the classes.

    Payment Service

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

    Cash Payment

    public interface IPayment {
     void executePayment();
    }
    
    public class CashPayment implements IPayment{
     public void executePayment() {
      System.out.println("Perform Cash Payment "); 
     }
    }
    
  3. Create JavaConfig class

    To create JavaConfig class you need to annotate it with @Configuration. When a class is annotated with @Configuration annotation the annotated class is identified as a configuration class. This configuration class will contain the @Bean annotated methods, these methods will provide details about the beans that are to be created and managed by the Spring application context.

    It's better to keep config classes in a separate package so create a new package and create the config class (I have named it AppConfig.java) there.

    package org.netjs.exp.config;
    
    import org.netjs.exp.Spring_Example.CashPayment;
    import org.netjs.exp.Spring_Example.IPayService;
    import org.netjs.exp.Spring_Example.IPayment;
    import org.netjs.exp.Spring_Example.PayServiceImpl;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class AppConfig {
     @Bean
     public IPayService payService(){
      PayServiceImpl payServiceImpl = new PayServiceImpl();
      payServiceImpl.setPayment(cashPayment());
      return payServiceImpl;
     }
     
     @Bean
     public IPayment cashPayment(){
      return new CashPayment(); 
     }
    }
    

    Here it can be seen how the methods that create the beans are annotated with @Bean annotation. Also note that in this configuration class I have given example of setter based dependency injection.

  4. Java class to run the application

    package org.netjs.exp.Spring_Example;
    
    import org.netjs.exp.config.AppConfig;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.support.AbstractApplicationContext;
    
    public class App 
    {
        public static void main( String[] args ){
         AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
            IPayService bean = (IPayService) context.getBean("payService");
            bean.performPayment();
            context.close();
        }
    }
    

    Here note that AnnotationConfigApplicationContext is used to create the Spring application context. It takes the JavaConfig class as input and search for all the beans in the configuration class by looking for the methods annotated with @Bean annotation.
    Another thing to note that is, by default the bean's id is the same as the name given to the method annotated with @Bean. That's why you can get the PayService bean using -

    context.getBean("payService");
    
    Because in the JavaConfig class method's name is payService. If you want to provide another name then you can use the name attribute. As example if you want to call the payService bean as myPayService then it can be done this way -
    @Bean(name="myPayService")
    public IPayService payService(){
     PayServiceImpl payServiceImpl = new PayServiceImpl();
     payServiceImpl.setPayment(cashPayment());
     return payServiceImpl;
    }
    
    And then it should be called as
     
    IPayService bean = (IPayService) context.getBean("myPayService");
    

As I mentioned above, the configuration done was for setter. If you want to use constructor dependency injection then you need to change it a little.

Suppose the PayService class is like this -
 
public class PayServiceImpl implements IPayService {
 
 private IPayment payment;
 public PayServiceImpl(IPayment payment){
  this.payment = payment;
 }
 
 public void performPayment() {
  payment.executePayment();
 }

}
Then in JavaConfig class we have to provide a constructor injection.
package org.netjs.exp.config;

import org.netjs.exp.Spring_Example.CashPayment;
import org.netjs.exp.Spring_Example.IPayService;
import org.netjs.exp.Spring_Example.IPayment;
import org.netjs.exp.Spring_Example.PayServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
 @Bean
 public IPayService payService(){
  return new PayServiceImpl(cashPayment());
 }
 
 @Bean
 public IPayment cashPayment(){
  return new CashPayment(); 
 }
}

That's all for this topic Spring example program using JavaConfig. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring example program using XML configuration
  2. Spring example program using automatic configuration
  3. What is Dependency Injection in Spring
  4. Dependency Injection using factory-method in Spring
  5. Bean definition inheritance in Spring
  6. Data access in Spring framework

You may also like -

>>>Go to Spring tutorial page

Tuesday, 6 October 2015

Creating a Maven project in Eclipse

This tutorial talks about how to create a Java project structure using Apache Maven. Here I am using the maven Eclipse plugin. These days Eclipse comes with maven plugin and you don't need to download and set up maven plugin yourself. To verify that you have maven plugin pre-configured in eclipse go to Windows - Preferences, there on the left side scrollable window search for Maven, if you have maven then it will look like this.

maven project in eclipse

Now coming back to our project structure note that I have used Eclipse luna 4.2.2 for this tutorial.

Creating project structure

Right click in Project Explorer, click New and then select Other

maven project in eclipse

That will open a Wizard, there select Maven and then Maven Project. Click Next.

maven project in eclipse

In the New Maven Project window, check Use default Workspace location. Click Next.

maven project in eclipse

In the next window "Select an archetype" select one with artifact ID "maven-archetype-quickstart" Click Next.

maven project in eclipse

In the next window provide group ID and artifact ID. Click Finish.

maven project in eclipse

That will create the project structure.

maven project in eclipse

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


Related Topics

  1. Spring example program using XML configuration
  2. Spring example program using JavaConfig and Annotations
  3. Spring example program using automatic configuration
  4. Autowiring using annotations in Spring

You may also like -