Autosizing columns in excel file in Java using POI

Autosizing columns in excel file in Java using POI

While creating excel files or reports many a times we require to auto resize the column with to accommodate the cell values and avoid overlapping of contents with adjacent cells, that will certainly look clumsy and not readable.

To auto resize column width according to its content, use autoSizeColumn method of HSSFSheet or XSSFSheet class. here is the code for this,


1
2
3
4
5
6
	HSSFWorkbook workbook = new HSSFWorkbook();
	HSSFSheet sheet = workbook.createSheet("SampleSheet");
	
	for(int count =0; count<15 count="" font="">
		sheet.autoSizeColumn((short) count);
	}


Note: autoSizeColumn must be called after the cell contents are set, otherwise it will have no impact.

Jackson Example for Json string convert to/from Java Object



Jackson is a very powerful JSON processor Java library. Jackson is used to convert the java objects to json, and json to java objects.

In below example we will try to explain how to convert JSON string to/from java object.
Before we start on main concept, first let’s setup library to use Jackson,

Jackson libraries can be added in 2 ways

1. For Maven dependencies, add below code to pom.xml to resolve Jackson dependency.


<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.0</version>
</dependency>
  

2.       For ANT and normal Java/JEE projects download below mentioned Jars from Jackson download page
a.  jackson-annotations-2.3.0.jar
b.  jackson-core-2.3.0.jar
c.  jackson-databind-2.3.0.jar

Let’s create POJO which needs to be converted to JSON.

class Employee implements Serializable {
       private static final long serialVersionUID = -588508412632489687L;
       private int id;
       private String name;
       private int age;

       public int getId() {
              return id;
       }

       public void setId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

       public int getAge() {
              return age;
       }

       public void setAge(int age) {
              this.age = age;
       }
      
       @Override
       public String toString() {
              return "ID:" + this.id + " Name:" + this.name + " Age:" + this.age;
       }
}


Now moving towards actual concept of converting JSON to/from Java object

Convert Java object to JSON:

Create a ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) instance as below,

ObjectMapper mapper = new ObjectMapper();

Create and initialize POJO object,
              Employee emp = new Employee();
              emp.setId(1);
              emp.setName("MP");
              emp.setAge(21);

Use writeValue method of ObjectMapper class to serialize object into JSON as below,

mapper.writeValue(new File("C:\\ Study\\JSon\\Emp.json"), emp);

JSON string is now written to file system in Emp.json file.
Similarly, you can convert List to JSON as well as below,

mapper.writeValue(new File("C:\\ Study\\JSon\\Emp.json"), list);

If you see JSON object in file it is in raw format, to have formatter JSON content use writerWithDefaultPrettyPrinter() method as below,

mapper.writerWithDefaultPrettyPrinter().writeValue(new File("C:\\ Study\\JSon\\Emp.json"), list);

Note: Make sure you define default constructor if parameterized is there, as Jackson uses default constructer to create instances of POJO. If default constructor is not present, it will throw JsonMappingException.
Convert JSON to Java Object

Employee e = mapper.readValue(new File("C:\\ Study\\JSon\\Emp.json"), new TypeReference>() {})


Please comment if you like this example.

How to make ArrayList or List Synchronized in Java

Synchronizing List implementation in Java:

In java, most of the collections are not synchronized, due to that these give reasonably fast performance. Many a times we need these collections (mostly List implementations) to be synchronized to write code in mutithreaded environment, for that there are 2 ways as below to achieve that,
1. Using Collections.synchronizedList method
2. Using CopyOnWriteArrayList instead of other List implementations, which is a synchronized implementation of List interface.

Below is a code snippet for Collections.synchronizedList






1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
	List stringList = Collections.synchronizedList(new ArrayList());
	stringList.add("One");
	stringList.add("Two");
	stringList.add("Three");
	stringList.add("Four");
	stringList.add("Five");
  
	System.out.println("Iterating synchronized ArrayList:");
	// when iterating over a synchronized list in multi-threaded, we need to synchronized access to the synchronized list
	synchronized (stringList) {
	  Iterator iterator = stringList.iterator();
	  while (iterator.hasNext())
	      System.out.println(iterator.next());
	}



Note: Iterator for List synchronized using Collections.synchronizedList must be used in synchrized block or method else it will throw ConcurrentModificationException.

Interview Questions on Core Java

This post will be dynamic, will keep on updating.

In this post i will be trying to post core java interview questions being asked for 4-5 years of experience.

1. Collections 

  • One might ask for difference between different type of collections like: ArrayList and LinkedList, Vector and ArrayList, HashMap and ConcurrentHashmap
  • Other typical question on collection will be to explain implementation of some of typical collections like: HashMap, ConcurrentHashmap etc.
2. Concurrency




Hope this will help.