Tagged: #list

How to iterate a List in Java

This tutorial shows several ways for iterating a List in Java. 1- Typical For loop Using a typical For loop, you can iterate a List as the following:

2- Enhanced For loop Since JDK 5.0, you can iterate a List using an enhanced For loop which works as the following:

3- Typical While loop Using a typical while...

Convert JSON to Java Object

This tutorials shows 2 ways for converting a JSON string to a Java object. 1- Gson Gson is the most popular library for converting JSON string to Java objects. With Gson, you can do the conversion in one line as the following:

Some points to be considered when using Gson: If the JSON string holds an invalid object attribute, then Gson implicitly...

Java – Convert List to comma-separated String

This tutorial shows several ways for converting a List to a comma-separated String in Java. 1- Java 7 The traditional way of converting a List to a comma-separated String in Java 7 and older versions is through using StringBuilder as the following:

2- Java 8 In Java 8, there are 2 conversion ways. 2.1. String.join() The most common way is...

Java – Convert comma-separated String to List

This tutorial shows several ways for converting a comma-separated String to a List in Java. 1- Java 7 With Java 7 and older versions, the typical way of converting a comma-separated String to a List is through splitting the String by the comma “,” delimiter and then generating a List using Arrays.asList() as the following:

2- Java 8 In...

Java – Convert List to Array

This tutorial shows several ways to convert a List to Array in Java. 1- toArray() List provides a utility method called toArray() which accepts an empty array and populates it with the elements of the array list.

In the above example, we initialize an array with the same number of elements as the input list, then we populate it...

Java – Convert Array to List

This tutorial shows several ways to convert Array to List in Java. 1- Arrays.asList You can convert an Array to List using Arrays.asList() utility method. This method accepts an array as input and returns a list as output.

The limitation of using this method is that it returns a fixed size list. You can just read and overwrite its...

Java – Convert List to Map

This tutorial shows the different ways to convert a List to Map in Java. 1- Java 7 & before With Java 7 and older releases, the only way to convert a List to Map is to iterate over the list and populate the map manually. In the following example, we implement a utility method which accepts a list of Student...