


Detailed explanation of sorting and filtering operations of JSON arrays in Java.
Detailed explanation of sorting and filtering operations of JSON arrays in Java
In Java development, processing JSON data is a common task. As one of the commonly used data structures, JSON array often requires sorting and filtering operations in practical applications. This article will introduce in detail the sorting and filtering operations of JSON arrays in Java and provide corresponding code examples.
1. Sorting operation of JSON array
- Use JSONArray object to store JSON array
In Java, using the json library to process JSON data is a common way. Among them, the json library provides the JSONArray class for storing JSON arrays.
First, we need to import the following dependencies:
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
Then, through the constructor method of the JSONArray class, convert the JSON string into a JSONArray object:
String jsonString = "[{"name":"Tom","age":30},{"name":"Jerry","age":20}]"; JSONArray jsonArray = new JSONArray(jsonString);
- Use Comparator interface for sorting
In Java, you can use the Comparator interface to define sorting rules. We can customize a Comparator object to specify which field to sort by. The sample code is as follows:
import java.util.Comparator; class UserComparator implements Comparator<JSONObject> { public int compare(JSONObject obj1, JSONObject obj2) { try { int age1 = obj1.getInt("age"); int age2 = obj2.getInt("age"); return Integer.compare(age1, age2); } catch (JSONException e) { e.printStackTrace(); return 0; } } }
In the above example, we customized a UserComparator class, implemented the Comparator interface, and overridden the compare method. The compare method returns the corresponding sorting results by getting the age field of two JSONObject objects, comparing their sizes.
- Sort the JSON array
With the Comparator object, we can sort the JSON array through the sort method of the Collections class. The sample code is as follows:
List<JSONObject> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { try { JSONObject obj = jsonArray.getJSONObject(i); list.add(obj); } catch (JSONException e) { e.printStackTrace(); } } Collections.sort(list, new UserComparator());
In the above example, each JSONObject object is added to a List by looping through the JSON array. Then, the List is sorted through the sort method of the Collections class, and the sorting rules are defined by the UserComparator object.
- Output the sorted results
Through the above operations, we have sorted the JSON array according to the specified sorting rules. Next, we can convert the sorted results into a JSON array and output it to the console. The sample code is as follows:
JSONArray sortedJsonArray = new JSONArray(list); System.out.println(sortedJsonArray.toString());
Convert the sorted results into JSON characters by calling the toString method of the JSONArray object string and output to the console.
2. JSON array filtering operation
- Use the Predicate interface for filtering
In Java 8 and above, you can use the Predicate interface for filtering filter operation. We can customize a Predicate object to specify filtering conditions. The sample code is as follows:
import java.util.function.Predicate; class AgeFilter implements Predicate<JSONObject> { public boolean test(JSONObject obj) { try { int age = obj.getInt("age"); return age >= 25; } catch (JSONException e) { e.printStackTrace(); return false; } } }
In the above example, we customized an AgeFilter class, implemented the Predicate interface, and overridden the test method. The test method obtains the age field of the JSONObject object, determines whether it is greater than or equal to 25, and returns the corresponding filtering result.
- Filtering the JSON array
With the Predicate object, we can filter the JSON array through the Stream API. The sample code is as follows:
List<JSONObject> filteredList = list.stream() .filter(new AgeFilter()) .collect(Collectors.toList());
In the above example, the List is converted into a Stream object by calling the stream method of the List object. Then, through the filter method of the Stream object, specify the Predicate object as the filtering rule, and use the collect method to collect the filtered results into another List.
- Output the filtered results
Through the above operations, we have filtered the JSON array according to the specified filtering rules. Next, we can convert the filtered results into a JSON array and output it to the console. The sample code is as follows:
JSONArray filteredJsonArray = new JSONArray(filteredList); System.out.println(filteredJsonArray.toString());
Convert the filtered results into JSON characters by calling the toString method of the JSONArray object string and output to the console.
Summary:
This article details the sorting and filtering operations of JSON arrays in Java and provides corresponding code examples. By sorting and filtering the JSON array, we can get the data we need based on actual needs. Using these operations can improve the efficiency and accuracy of our processing of JSON data. I hope this article will be helpful to readers in actual development.
The above is the detailed content of Detailed explanation of sorting and filtering operations of JSON arrays in Java.. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.