Skip to main content

Welcome to Geoff Hayward's Weblog

Commenting on Java, JavaFX, Java EE, Joomla, and IoT.

You can convert an ArrayList to a Java EE JsonArray using the Java Stream API in the following way.

// set up example
ArrayList<Pet> pets = new ArrayList<>();
pets.add(new Pet("Goldie", "Fish"));
pets.add(new Pet("Daisy", "Cow"));
pets.add(new Pet("Snowball", "Cat"));

// the work
	.map((a) -> { 
		return Json.createObjectBuilder()
			.add("id", a.getName())
			.add("type", a.getGroup())

The .map operation of the stream API takes a Function<T,R>. The function converts each item to a JsonObject. Then the .collect operation creates the JsonArray using each of the JsonObjects.

I hope you find this useful.


In an earlier post this year, 'Convert an ArrayList to an Array in Java', I commented on a way to convert an ArrayList to an Array in Java. Here is the example code from the earlier post.

List<String> results = new ArrayList<>();
results.toArray(new String[results.size()]);

This earlier way works fine, however it's old school. Here is the Java 8 Lambda way to convert an ArrayList to an Array:

Long[] longArray =

This example works by mapping a new object for each item in the ArrayList's stream to the new stream, and then collecting that stream as an array.


Mailing List

Responsive Media

With the ResponsiveMedia plugin for Joomla it is easy to add 3rd party content from YouTube, Vimeo, and Instagram right in to any Joomla! article.