A photo of Geoffrey Hayward

Java Stream API: ArrayList to JsonArray

Published February 3, 2017

Illustration of Java code converting an ArrayList to a JsonArray, displayed on a simple and clean background.

You can convert an ArrayList to a Java EE JsonArray using a Java Stream 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
pets.stream()
	.map((a) -> { 
		return Json.createObjectBuilder()
			.add("id", a.getName())
			.add("type", a.getGroup())
			.build();
	})
	.collect(
		Json::createArrayBuilder,
		JsonArrayBuilder::add,
		JsonArrayBuilder::add
	)
	.build();

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.

Latest Posts

Illustration representing a Hugo website migration from Cloudflare Pages to Cloudflare Workers with Decap CMS and GitHub authentication.

Moving from Cloudflare Pages to Workers

May 31, 2026

Computing

I moved my Hugo site from Cloudflare Pages to Cloudflare Workers. The migration was mostly straightforward, but a few small details were worth writing down.

Continue reading
Digital illustration of a magnifying glass highlighting a glowing green “9:00” timestamp in computer logs, representing a detective-style investigation of suspicious traffic.

Is Chromium Omaha Updater Bringing Your Site or Service Down

September 19, 2025

Computing

For the last two weeks or so, every day at 9:00 a.m. one of the major UK National Health Service ‘NHS’ websites, I work on, has been getting hit by something strange and was on the brink each time. The regularity of 9:00 a.m. was suspicious.

Continue reading
A simple graph that says configure Terraform Cloud to assume an AWS IAM role via OIDC.

Configure Terraform Cloud to Assume an AWS IAM Role via OIDC

June 11, 2025

Computing

Here is how to configure Terraform Cloud to assume an AWS IAM role via OIDC (OpenID Connect) using only environment variables—no static AWS keys are required.

Continue reading