Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

1. Overview

JSON is a widely employed structured data format typically used in most modern APIs and data services. It’s particularly popular in web applications due to its lightweight nature and compatibility with JavaScript.

Sometimes, it may be useful to sort the data before we display it in applications that fetch JSON.

In this quick tutorial, we’ll see a couple of approaches for sorting JSON objects in Java.

2. Getting Started

Let’s get started by defining a relatively simple JSON structure which models some imaginary Solar Events:

{
    "solar_events": [
        {
            "event_name": "Solar Eclipse",
            "date": "2024-04-08",
            "coordinates": {
                "latitude": 37.7749,
                "longitude": -122.4194
            },
            "size": "Large",
            "speed_km_per_s": 1000
        },
        {
            "event_name": "Solar Flare",
            "date": "2023-10-28",
            "coordinates": {
                "latitude": 0,
                "longitude": 0
            },
            "size": "Small",
            "speed_km_per_s": 100
        },
        {
            "event_name": "Sunspot",
            "date": "2023-11-15",
            "coordinates": {
                "latitude": 15,
                "longitude": -75
            },
            "size": "Large",
            "speed_km_per_s": 1500
        },
        {
            "event_name": "Coronal Mass Ejection",
            "date": "2024-01-10",
            "coordinates": {
                "latitude": -5,
                "longitude": 80
            },
            "size": "Medium",
            "speed_km_per_s": 500
        }
    ]
}

Throughout this tutorial, this JSON document will be the focus of our examples.

3. Using Jackson

In this first example, we’ll take a look at Jackson a multi-purpose Java library for processing JSON data.

First, we’ll need to add the jackson-databind dependency to our pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.2</version>
</dependency>

We’ll also need to define a few simple POJO objects that we can use to deserialize our JSON string into a Java object:

class SolarEvent {
    @JsonProperty("event_name")
    private String eventName;
    @JsonProperty("date")
    private String date;
    @JsonProperty("coordinates")
    private Coordinates coordinates;
    @JsonProperty("type")
    private String type;
    @JsonProperty("class")
    private String eventClass;
    @JsonProperty("size")
    private String size;
    @JsonProperty("speed_km_per_s")
    private int speedKmPerS;

    // Getters and Setters
}

class Coordinates {
    @JsonProperty("latitude")
    private double latitude;

    @JsonProperty("longitude")
    private double longitude;

    // Getters and setters
}

We’ll also define a container object to hold our list of events:

class SolarEventContainer {
    @JsonProperty("solar_events")
    private List<SolarEvent> solarEvents;

    //Getters and setters
}

Now, we can go ahead and write a simple unit test to verify we can sort a list of solar events using a given attribute:

@Test
void givenJsonObjects_whenUsingJackson_thenSortedBySpeedCorrectly() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    SolarEventContainer container =
      objectMapper.readValue(new File("src/test/resources/solar_events.json"),
      SolarEventContainer.class);

    List<SolarEvent> events = container.getSolarEvents();
    Collections.sort(events, Comparator.comparingInt(event -> event.getSpeedKmPerS()));

    assertEquals(100, events.get(0).getSpeedKmPerS());
    assertEquals(500, events.get(1).getSpeedKmPerS());
    assertEquals(1000, events.get(2).getSpeedKmPerS());
    assertEquals(1500, events.get(3).getSpeedKmPerS());
}

Our first goal is to parse the JSON and deserialize it into our object model. For this, we’ve used Jackson’s standard ObjectMapper. We used the readValue() method to read the JSON from a file and convert our JSON into a SolarEventContainer object.

Now that we have a Java object model, we can go ahead and sort the objects based on any of the attributes in our class. For the sorting, we define a Comparator by using a lambda expression, and the comparingInt() static factory to sort our events using the getSpeedKmPerS() method.

Finally, our test confirmed that the speed attribute correctly ordered the events.

4. Using Gson

Now, let’s take a look at a similar approach using another popular JSON processing library Gson. As before, we’ll start by adding this dependency to our pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.11.0</version>
</dependency>

As always, the latest version is available from the Maven Repository.

Sometimes, it might not always be possible to have our own internal Java object model to work with, so in this example, we’ll see how we can work with the JSON Java objects that are available directly from this library:

@Test
public void givenJsonObject_whenUsingGson_thenSortedBySizeCorrectly() throws FileNotFoundException {
    JsonReader reader = new JsonReader(new FileReader("src/test/resources/solar_events.json"));
    JsonElement element = JsonParser.parseReader(reader);
    JsonArray events = element.getAsJsonObject().getAsJsonArray("solar_events");
    List<JsonElement> list = events.asList();

    Collections.sort(list, (a, b) -> {
        double latA = a.getAsJsonObject()
          .getAsJsonObject("coordinates")
          .get("latitude")
          .getAsDouble();
        double latB = b.getAsJsonObject()
          .getAsJsonObject("coordinates")
          .get("latitude")
          .getAsDouble();
        return Double.compare(latA, latB);
    });

    assertEquals(-5, getJsonAttributeAsInt(list.get(0)));
    assertEquals(0, getJsonAttributeAsInt(list.get(1)));
    assertEquals(15, getJsonAttributeAsInt(list.get(2)));
    assertEquals(37, getJsonAttributeAsInt(list.get(3)));
}

private int getJsonAttributeAsInt(JsonElement element) {
    return element.getAsJsonObject()
      .getAsJsonObject("coordinates")
      .get("latitude")
      .getAsInt();
}

As we can see, we use a similar approach to read in our sample JSON file, but this time, we retrieve a list of JsonElement objects, which represents each entry in our solar_events.json file.

Likewise, we can now sort the elements in the list using the Collections.sort method by supplying a custom comparator to parse and select the required values from the JSON objects. This is certainly a bit more verbose than the previous example and vulnerable to errors if our JSON structure changes or we mistype a JSON object or attribute name.

Finally, this time around, we check the elements have been sorted correctly using the latitude value. We also provide a small utility method to help us extract the values from the JSON elements.

5. Conclusion

In this short article, we learned how to sort JSON objects using two popular JSON processing Java libraries.

In the first example, we saw how to use our own Java object model with the popular Jackson library. Latterly, we learned how to work directly with the object model supplied by the Gson library.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)