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
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

For those of you that do not know the JSON format; JSON stands for JavaScript Object Notation and is a very powerful and fast way of getting and using data. It is fast because the client does not need to parse it unlike XML. At your keyboarding finger tips you have a JavaScript collection ready to roll. But the best part of it is it circumvents the cross domain malarkey. That's right no proxy needed.

So let me give you a demo using a well-known website that lets you feed on their data. Of course this demo is only a demo and I would not use script tags in the body of the document if it was a live website.

<div id="twitter"><!-- a Handle --></div>
 
// This function must be known before the call
function getTweets(data)
{
    var html = '';
    for (var i = 0; i < data.length; i++){
        html += '<p>' + data[i].text + '</p>';
    }
    document.getElementById('twitter').innerHTML = html;
}
 
<script type="text/javascript" src="https://twitter.com/statuses/user_timeline.json?screen_name=YOURUSERNAME&callback=getTweets" ></script>

The example I created about will right out the main text from all of your tweets paragraph by paragraph thus demonstrating the elegance of JSON. Try it yourself but, remember to check the API of the data feed you are getting JSON from to see what tasty nibbles are in store.



Read

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.

ResponsiveMedia