Java Stream API: ArrayList to JsonArray
03 January 2017
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 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.
Read : Java Stream API: ArrayList to JsonArray
The Java 8 Lambda way: ArrayList to an Array
15 July 2016
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 = longArrayList.stream() .map(Long::new) .toArray(Long[]::new);
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.
Read : The Java 8 Lambda way: ArrayList to an Array