Java Collections – ArrayList

How to properly create and use an ArrayList including adding, retrieving and modifying items.

Check out the previous parts of this Java Collections Guide: Introduction, Part 1 – Collection and Part 2 – Sets.

1. Introduction

The ArrayList is one of the most widely used classes in the Java Collections Framework (if not the entire JDK; that position probably belongs to String). It provides a simple array-like storage of items with dynamically adjusting capacity. In this article, we present some usage patterns of the List and ArrayList.

Continue reading “Java Collections – ArrayList”

How to Convert CSV to JSON in Java

Convert CSV to JSON using Jackson. Use a POJO for conversion or a List & Map for intermediate storage.

“Any fool can know. The point is to understand.”
― Albert Einstein

 

1. Introduction

CSV to JSON conversion is easy. In this article, we present a couple of methods to parse CSV data and convert it to JSON. The first method defines a POJO and uses simple string splitting to convert CSV data to POJO, which in turn is serialized to JSON. The second method uses a more complete CSV parser with support for quoted fields and commas embedded within fields. In this method, we use the Java Collection classes to store the parsed data and convert those to JSON.

Continue reading “How to Convert CSV to JSON in Java”

Java Collections – Set

A Set is a container which does not allow duplicate elements. Common Set implementations include HashSet, LinkedHashSet and TreeSet.

“Quotation, n: The act of repeating erroneously the words of another.”
― Ambrose Bierce, The Unabridged Devil’s Dictionary

Check out the earlier parts of this Java Collections Series: Introduction and Part 1.

1. Introduction

A Set is a container which does not contain duplicate elements. The item method equals() is used to determine whether the object is already present in the Set. At most one null element is allowed in the Set.

Continue reading “Java Collections – Set”

Java Collections – Part 1

Java Collections Framework: learn about adding items, iterating over a collection and removing items.

“Success is not final, failure is not fatal: it is the courage to continue that counts.”
― Winston S. Churchill

Check out the first part of this Java Collections Series: Introduction.

1. Introduction

Let us learn about Java Collections and the various operations applicable to collections in general. Since the Collection interface is implemented by most of the classes in the Collections Framework (except Map and friends), the methods described here apply to all those classes.

Continue reading “Java Collections – Part 1”

Java Collections

Java Collections Framework: An Introduction to the class hierarchy.

“Any fool can know. The point is to understand.”
― Albert Einstein

1. Introduction

Java Collections Framework is an architecture for storing, managing and manipulating collections of objects. It provides many data structures and algorithms commonly used for dealing with collections. For example: searching and sorting. Many details about storing objects are abstracted away (meaning you do not have to deal with it in code). An unified interface is provided to manipulate them e.g for adding and removing entries.

Continue reading “Java Collections”

Apache POI Excel Example – Part 2

More formatting options using Java with Apache POI for Microsoft Excel spreadsheets.

1. Introduction

In Part 1 of this Apache POI Excel guide, we examined how to create an Excel spreadsheet and add data to it. We also looked at properly storing data into cells to avoid “Number Stored as Text” errors.

In this chapter, let us look at some more options for formatting data within an Excel spreadsheet.

Continue reading “Apache POI Excel Example – Part 2”

Java HashMap Examples

1. Introduction

A HashMap is a map of keys to values which uses a hash table for implementation. The HashMap organizes the keys into buckets based on the value of the hashCode() of the key. It provides constant-time performance for get and put operations. What this means is that the time taken by get and put operations does not depend on the size of the map.

Continue reading “Java HashMap Examples”

Java Math.random Examples

Math.Random

1. Introduction

Let us learn how to generate some random numbers in Java. Random numbers are needed for various purposes; maybe you want to generate a password or a session identifier. Whatever the purpose may be, there are a number of issues to be aware of when generating a random number.

Continue reading “Java Math.random Examples”

Java String Format Examples

1. Introduction

Have you tried to read and understand Java’s String format documentation? I have and found it hard to understand. While it does include all the information, the organization leaves something to be desired.

This guide is an attempt to bring some clarity and ease the usage of string formatting in java.

Learn about string formatting in python? Check out this article.

2. String Formatting

Most common way of formatting a string in java is using String.format(). If there were a “java sprintf”, this would be it.

String output = String.format("%s = %d", "joe", 35);

For formatted console output, you can use printf() or the format() method of System.out and System.err PrintStreams.

System.out.printf("My name is: %s%n", "joe");

Create a Formatter and link it to a StringBuilder. Output formatted using the format() method will be appended to the StringBuilder.

StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format("PI = %f%n", Math.PI);
System.out.print(sbuf.toString());
// you can continue to append data to sbuf here.

3. Format Specifiers

Here is a quick reference to all the conversion specifiers supported.

Specifier Applies to Output
%a floating point (except BigDecimal) Hex output of floating point number
%b Any type “true” if non-null, “false” if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) Decimal Integer
%e floating point decimal number in scientific notation
%f floating point decimal number
%g floating point decimal number, possibly in scientific notation depending on the precision and value.
%h any type Hex String of value from hashCode() method.
 %n none Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Octal number
%s any type String value
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint) Hex string.

3.1. Date and Time Formatting

Note: Using the formatting characters with “%T” instead of “%t” in the table below makes the output uppercase.

 Flag Notes
 %tA Full name of the day of the week, e.g. “Sunday“, “Monday
 %ta Abbreviated name of the week day e.g. “Sun“, “Mon“, etc.
 %tB Full name of the month e.g. “January“, “February“, etc.
 %tb Abbreviated month name e.g. “Jan“, “Feb“, etc.
 %tC Century part of year formatted with two digits e.g. “00” through “99”.
 %tc Date and time formatted with “%ta %tb %td %tT %tZ %tY” e.g. “Fri Feb 17 07:45:42 PST 2017
 %tD Date formatted as “%tm/%td/%ty
 %td Day of the month formatted with two digits. e.g. “01” to “31“.
 %te Day of the month formatted without a leading 0 e.g. “1” to “31”.
%tF ISO 8601 formatted date with “%tY-%tm-%td“.
%tH Hour of the day for the 24-hour clock e.g. “00” to “23“.
%th Same as %tb.
%tI Hour of the day for the 12-hour clock e.g. “01” – “12“.
%tj Day of the year formatted with leading 0s e.g. “001” to “366“.
%tk Hour of the day for the 24 hour clock without a leading 0 e.g. “0” to “23“.
%tl Hour of the day for the 12-hour click without a leading 0 e.g. “1” to “12“.
%tM Minute within the hour formatted a leading 0 e.g. “00” to “59“.
%tm Month formatted with a leading 0 e.g. “01” to “12“.
%tN Nanosecond formatted with 9 digits and leading 0s e.g. “000000000” to “999999999”.
%tp Locale specific “am” or “pm” marker.
%tQ Milliseconds since epoch Jan 1 , 1970 00:00:00 UTC.
%tR Time formatted as 24-hours e.g. “%tH:%tM“.
%tr Time formatted as 12-hours e.g. “%tI:%tM:%tS %Tp“.
%tS Seconds within the minute formatted with 2 digits e.g. “00” to “60”. “60” is required to support leap seconds.
%ts Seconds since the epoch Jan 1, 1970 00:00:00 UTC.
%tT Time formatted as 24-hours e.g. “%tH:%tM:%tS“.
%tY Year formatted with 4 digits e.g. “0000” to “9999“.
%ty Year formatted with 2 digits e.g. “00” to “99“.
%tZ Time zone abbreviation. e.g. “UTC“, “PST“, etc.
%tz Time Zone Offset from GMT e.g. “-0800“.

4. Argument Index

An argument index is specified as a number ending with a “$” after the “%” and selects the specified argument in the argument list.

String.format("%2$s", 32, "Hello");
// prints: "Hello"

5. Formatting an Integer

With the %d format specifier, you can use an argument of all integral types including byte, short, int, long and BigInteger.

Default formatting:
String.format("%d", 93);
// prints 93
Specifying a width:
String.format("|%20d|", 93);
// prints: |                  93|
Left-justifying within the specified width:
String.format("|%-20d|", 93);
// prints: |93                  |
Pad with zeros:
String.format("|%020d|", 93);
// prints: |00000000000000000093|
Print positive numbers with a “+”:

(Negative numbers always have the “-” included):

String.format("|%+20d|', 93);
// prints: |                 +93|
A space before positive numbers.

A “-” is included for negative numbers as per normal.

String.format("|% d|", 93);
// prints: | 93|

String.format("|% d|", -36);
// prints: |-36|
Use locale-specific thousands separator.

For the US locale, it is “,”:

String.format("|%,d|", 10000000);
// prints: |10,000,000|
Enclose negative numbers within parantheses (“()”) and skip the “-“:
String.format("|%(d|", -36);
// prints: |(36)|
Octal Output
String.format("|%o|"), 93);
// prints: 135
Hex Output
String.format("|%x|", 93);
// prints: 5d
Alternate Representation for Octal and Hex Output

Prints octal numbers with a leading “0” and hex numbers with leading “0x“.

String.format("|%#o|", 93);
// prints: 0135

String.format("|%#x|", 93);
// prints: 0x5d

String.format("|%#X|", 93);
// prints: 0X5D

6. String and Character Conversion

Default formatting:

Prints the whole string.

String.format("|%s|", "Hello World");
// prints: "Hello World"
Specify Field Length
String.format("|%30s|", "Hello World");
// prints: |                   Hello World|
Left Justify Text
String.format("|%-30s|", "Hello World");
// prints: |Hello World                   |
Specify Maximum Number of Characters
String.format("|%.5s|", "Hello World");
// prints: |Hello|
Field Width and Maximum Number of Characters
String.format("|%30.5s|", "Hello World");
|                         Hello|

Summary

This guide explained String formatting in Java. We covered the supported format specifiers. Both numeric and string formatting support a variety of flags for alternative formats.