Sorting JSON data using Java Streams is useful when working with API responses, configuration files, or stored data. Let’s break it down step by step.
Steps to Sort JSON Data Using Streams
- Read the JSON file or API response
- Parse JSON into Java Objects (
List<T>
) using Jackson - Use
stream().sorted()
to sort the data - Collect the sorted data back into a list
- Write the sorted data back to a file (Optional)
Sample JSON Data (employees.json
)
We have a list of employees in a JSON file.
[
{ "name": "John", "age": 30, "salary": 50000 },
{ "name": "Alice", "age": 25, "salary": 70000 },
{ "name": "Bob", "age": 28, "salary": 60000 }
]
We will sort employees based on salary (Descending Order).
Reading & Sorting JSON in Java
Step 1: Define the Employee Class
class Employee {
public String name;
public int age;
public int salary;
public Employee() {} // Default constructor for Jackson
public String toString() {
return name + " (Age: " + age + ", Salary: $" + salary + ")";
}
}
Jackson requires a no-argument constructor for deserialization.
Step 2: Read, Parse, and Sort JSON Data
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.File;
import java.util.List;
import java.util.Comparator;
import java.util.stream.Collectors;
public class JsonSortingExample {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper(); // Jackson ObjectMapper
// Step 1: Read JSON file into List<Employee>
List<Employee> employees = objectMapper.readValue(
new File("employees.json"),
new TypeReference<List<Employee>>() {}
);
// Step 2: Sort employees by salary in descending order
List<Employee> sortedBySalary = employees.stream()
.sorted(Comparator.comparing(Employee::salary).reversed())
.collect(Collectors.toList());
// Step 3: Print sorted list
sortedBySalary.forEach(System.out::println);
}
}
Output (Sorted by Salary – Descending):
Alice (Age: 25, Salary: $70000)
Bob (Age: 28, Salary: $60000)
John (Age: 30, Salary: $50000)