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

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
Developer with laptop and friendly robot assistant outdoors, coding with Spring Boot.

Responsible AI Coding: What I’ve Learned So Far

May 9, 2025

Computing

A whole new way of coding. When JetBrains offered me a trial of Junie, an AI assistant built into IntelliJ, I had to give it a go. I soon saw the potential, it’s kind of like an AI coding partner (albeit a little dumb at times), but that’s okay, if used responsibly. So here’s what I’ve learned about coding responsibly with AI—so far.

Continue reading
And abstract image of programming code surrounded by a light bulb.

Notes on Successfully Running Ubuntu in VirtualBox

January 26, 2024

Computing

As a Software Developer who likes to use Ubuntu for Development but can sometimes only run it as just another window in Windows, I would like to share some nuanced VirtualBox configurations I built up over the years.

Continue reading