Problem: Using Java 8 Streams, how do you find the third longest word in a list without manually sorting and looping through?
✅ Example:
import java.util.Arrays;
import java.util.List;
public class ThirdLongestWord {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "mango", "kiwi");
words.stream()
.sorted((w1, w2) -> Integer.compare(w2.length(), w1.length())) // Sort by length descending
.skip(2) // Skip the first two longest words
.findFirst() // Get the 3rd longest word
.ifPresent(System.out::println);
}
}
✅ Output:
apple
✅Explanation:
The list of words: ["apple", "banana", "cherry", "mango", "kiwi"]
After sorting by length in descending order: ["banana", "cherry", "apple", "mango", "kiwi"]
Problem: How can you find the 3rd largest element from an integer array using Java 8 Streams?
✅ Correct Code Example:
import java.util.Arrays;
import java.util.Comparator;
public class NthLargestElement {
public static void main(String[] args) {
int[] arr = {12, 4, 3, 1, 9, 657};
int n = 3; // Find the 3rd largest element
Arrays.stream(arr)
.boxed() // Convert int to Integer for Comparator
.sorted(Comparator.reverseOrder()) // Sort in descending order
.skip(n - 1) // Skip first (n - 1) largest elements
.findFirst() // Get the nth largest element
.ifPresent(System.out::println);
}
}
✅ ✅ Example Output:
9
✅ ✅ Explanation:
Step 1 – Stream Creation: Arrays.stream(arr) Creates an IntStream from the integer array [12, 4, 3, 1, 9, 657].
Step 2 – Boxing: .boxed() Converts IntStream to Stream<Integer> so we can use Comparator.reverseOrder().
Step 3 – Sorting in Descending Order: .sorted(Comparator.reverseOrder()) After sorting, the stream becomes: [657, 12, 9, 4, 3, 1].
Step 4 – Skip Elements: .skip(n - 1) Skip the first two elements (657 and 12) to get to the 3rd largest.
Step 5 – Get the Nth Largest: .findFirst() Picks the next element in the stream, which is 9.
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class NthLargestElement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = {12, 4, 3, 1, 9, 657};
System.out.print("Enter the value of n (e.g., 3 for 3rd largest): ");
int n = scanner.nextInt();
if (n <= 0 || n > arr.length) {
System.out.println("Invalid input! n must be between 1 and " + arr.length);
} else {
Arrays.stream(arr)
.boxed() // Convert int to Integer for Comparator
.sorted(Comparator.reverseOrder()) // Sort in descending order
.skip(n - 1) // Skip first (n - 1) elements
.findFirst() // Pick the nth largest element
.ifPresent(System.out::println);
}
scanner.close();
}
}
✅ Sample Run Example:
Input (User types):
3
Output:
9
✅ Explanation:
We use Scanner to take user input for n.
We validate n to ensure it is within the correct range: if (n <= 0 || n > arr.length)
We apply the same stream logic:
Sort in descending order.
Skip the first (n - 1) elements.
Return the nth largest element.
The result is printed using .ifPresent(System.out::println).
Problem: How do you check whether a string is a palindrome using Java 8 Streams (without reversing it)? A palindrome is a string that reads the same forwards and backwards — like “madam” or “level”
✅Example 1: Without Reverse
import java.util.stream.IntStream;
public class PalindromeCheckStream {
public static void main(String[] args) {
String input = "madam";
boolean isPalindrome = IntStream.range(0, input.length() / 2)
.allMatch(i -> input.charAt(i) == input.charAt(input.length() - 1 - i));
System.out.println("String is Palindrome: " + isPalindrome);
}
}
✅ Output:
String is Palindrome: true
✅ Explanation:
We use IntStream.range(0, input.length() / 2) to generate a stream of indices from 0 to input.length() / 2 - 1.
For each index i, we check: input.charAt(i) == input.charAt(input.length() - 1 - i) This compares the character from the start of the string with the corresponding character from the end.
.allMatch() returns true if all comparisons pass (i.e., the string is a palindrome).
We only check up to half the string because beyond that would be redundant.
✅ Alternative Approach – Using StringBuilder (without using explicit loops):
import java.util.stream.IntStream;
public class PalindromeCheckStream {
public static void main(String[] args) {
String input = "Java knowledge Base";
// Normalize the string: remove spaces and convert to lower case for accurate comparison
String normalizedInput = input.replaceAll("\\s+", "").toLowerCase();
boolean isPalindrome = normalizedInput.equals(
new StringBuilder(normalizedInput).reverse().toString()
);
System.out.println("Input Parameter: " + input);
System.out.println("String is Palindrome: " + isPalindrome);
}
}
✅Output:
Input Parameter: Java knowledge Base
String is Palindrome: false
✅ Explanation:
First, we normalize the string by:
Removing spaces (replaceAll("\\s+", ""))
Converting to lowercase (toLowerCase()) This ensures a fair comparison (ignoring case and spaces).
Then, we use StringBuilder’s .reverse() method and check: normalizedInput.equals(new StringBuilder(normalizedInput).reverse().toString());
This returns true if the normalized string is the same when reversed, and false otherwise.
When working with JSON, the most common approach is to bind JSON data directly to Java POJOs (Plain Old Java Objects) using Jackson’s data binding feature. However, sometimes the structure of the incoming JSON is dynamic, unknown, or too flexible to predefine Java classes. In these cases, Jackson’s Tree Model API comes in handy by allowing us to parse JSON into a tree structure that can be traversed dynamically.
1.What Is the Tree Model (JsonNode)?
The Tree Model allows us to parse JSON into a tree of JsonNode objects.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTreeModelExample {
public static void main(String[] args) {
try {
String json = "{ \"name\": \"Ashish Kumar\", \"age\": 30, \"address\": { \"city\": \"Delhi\", \"zipcode\": \"110001\" }, \"skills\": [\"Java\", \"Spring Boot\", \"Jackson\"] }";
ObjectMapper objectMapper = new ObjectMapper();
// Parse JSON into a tree of JsonNode
JsonNode rootNode = objectMapper.readTree(json);
// Access simple properties
String name = rootNode.get("name").asText();
int age = rootNode.get("age").asInt();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
// Access nested object
JsonNode addressNode = rootNode.get("address");
String city = addressNode.get("city").asText();
String zipcode = addressNode.get("zipcode").asText();
System.out.println("City: " + city);
System.out.println("Zipcode: " + zipcode);
// Access array
JsonNode skillsNode = rootNode.get("skills");
System.out.print("Skills: ");
for (JsonNode skill: skillsNode) {
System.out.print(skill.asText() + ",");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
✔️ Expected Output:
Name: Ashish Kumar
Age: 30
City: Delhi
Zipcode: 110001
Skills: Java Spring Boot Jackson
✅ Detailed Explanation of the Process
✔ Parsing JSON:
objectMapper.readTree(json) reads the entire JSON string and creates a tree of JsonNode objects.
rootNode represents the root of the tree.
✔ Accessing Simple Properties:
rootNode.get("name").asText() extracts the "name" property as a String.
rootNode.get("age").asInt() extracts the "age" property as an integer.
✔ Accessing a Nested Object:
rootNode.get("address") returns a JsonNode representing the "address" object.
Then we extract individual fields from addressNode:
addressNode.get("city").asText()
addressNode.get("zipcode").asText()
✔ Accessing Array Elements:
rootNode.get("skills") returns a JsonNode representing the JSON array.
Iterating through the array elements using a for-each loop and accessing each skill’s value with skill.asText().
✅ Advantages of Tree Model
Advantage
Explanation
Dynamic Parsing
No need to create Java classes in advance. Useful for unknown or changing JSON structures.
Selective Data Access
Access only the parts of the JSON you need, saving memory and effort.
Nested and Array Support
Easily traverse deeply nested objects and arrays without mapping everything upfront.
✅ When to Use Tree Model vs Data Binding
Scenario
Recommended Approach
Static and well-defined structure
Use POJOs + ObjectMapper (Serialization/Deserialization)
Unknown, dynamic, or partial structure
Use Tree Model (JsonNode)
Need to modify part of the JSON
Use ObjectNode (which extends JsonNode) to manipulate fields
4. Creating JSON Objects Dynamically with ObjectNode
In some scenarios, you don’t have a predefined Java object (POJO) to represent the JSON you want to generate. For example, when building dynamic JSON responses in REST APIs, or transforming data on the fly. Jackson’s ObjectNode class is ideal for such cases.
✅ What Is ObjectNode?
ObjectNode is a subclass of JsonNode that represents a JSON object { ... }.
Allows you to dynamically create, modify, and remove fields without needing a POJO.
Ideal when you want to construct a JSON object programmatically
✅ Demonstrates how to create simple fields using put().
✅ Shows how to add a nested object with ObjectNode.
✅ Explains how to build an array field using ArrayNode.
✅ Illustrates use cases like building dynamic JSON responses in REST APIs, building configuration files dynamically, or performing data transformations.
5. Working with JSON Arrays in Java
A JSON Array is an ordered collection of values, which may include objects, strings, numbers, booleans, or other primitives. In Java, using Jackson, you can easily parse and construct JSON arrays with the help of the ArrayNode class, which extends JsonNode.
Imagine you receive a JSON array from an external API that lists products available in an online store. You can parse the JSON array string into an ArrayNode and iterate through its elements like this:
Suppose your application needs to dynamically build a product catalog before returning it as a JSON response. You can use ArrayNode to construct the array programmatically:
👉 In a real-time e-commerce system, this dynamic creation of product lists allows you to build flexible APIs that respond with the most up-to-date product information in INR.
6. Choosing Between ArrayNode and JsonNode
When working with JSON data using Jackson, knowing when to use ArrayNode versus JsonNode helps you write cleaner, more efficient, and maintainable code.
✅ Use ArrayNode when:
You are working with a JSON structure where you know the data is always an array.
You need to perform specific operations on array elements, such as filtering, sorting, or mapping.
The structure is well-defined, and you want to work directly with array-specific methods (like .add(), .remove(), .size(), etc.).
✅ Use JsonNode when:
You are dealing with dynamic or nested JSON structures, where some fields could be arrays, objects, or primitive values.
You need a flexible and generic approach to process JSON without assuming a strict structure.
You want to parse arbitrary JSON data and explore it at runtime, especially when the schema is not predefined.
👉 Choosing the right type between ArrayNode and JsonNode helps improve code clarity and performance in your application.
7. Difference Between get()and path() in Jackson Tree Model
When working with the Jackson Tree Model (JsonNode), you often need to access specific fields or nested data in a JSON structure. Two commonly used methods for this are .get() and .path(). Understanding their differences helps you write more robust and error-resistant code.
7.1 get(String fieldName)
Behavior: Returns the value of the specified field as a JsonNode.
If the field does not exist: It returns null.
Use Case: When you are sure the field exists and want to get the exact node.
Example:
JsonNode nameNode = rootNode.get("name"); // returns null if "name" field is missing
⚠️ Risk: If you immediately call .asText() or .asInt() after .get(), and the field does not exist (i.e., null is returned), you will get a NullPointerException.
7.2 path(String fieldName)
Behavior: Returns the value of the specified field as a JsonNode.
If the field does not exist: Returns a missing node (MissingNode), which is a special JsonNode that does not throw NullPointerException and safely returns default values.
Example:
JsonNode nameNode = rootNode.path("name"); // Returns MissingNode if "name" does not exist
String name = nameNode.asText(); // Returns "" (empty string) if missing
⚡ Advantages of path()
✔ Safe Access Without NullPointerException Even if the field doesn’t exist, path() ensures that your code doesn’t throw a NullPointerException. Instead, it returns a MissingNode, and calling .asText(), .asInt(), etc., returns sensible defaults:
.asText() → ""
.asInt() → 0
✔ More Robust for Dynamic or Uncertain JSON Structures In real-world applications where the JSON structure might change or fields may be missing, using .path() prevents your code from breaking unexpectedly.
✅ Example Comparison
// Using get() – Potential NullPointerException
String name = rootNode.get("name").asText(); // Works if "name" exists
String phone = rootNode.get("phone").asText(); // Throws NullPointerException if "phone" is missing
// Using path() – Safe even if field missing
String name = rootNode.path("name").asText(); // Returns "Ashish Kumar"
String phone = rootNode.path("phone").asText(); // Returns "" (empty string)
Note :
📦 When Was path() Introduced?
The path() method has been available since early versions of Jackson (introduced around Jackson 2.x series) and has become a standard best practice for safely accessing JSON tree nodes when the presence of fields is not guaranteed.
🎯 Conclusion
Jackson’s Tree Model API is a powerful and flexible approach for handling JSON data in Java, especially when working with dynamic, unknown, or partially structured JSON. Unlike the traditional POJO-based data binding approach, the Tree Model provides the ability to parse JSON into a tree of JsonNode objects, enabling dynamic traversal, selective data access, and easy manipulation of JSON content.
By using ObjectNode and ArrayNode, developers can dynamically construct JSON objects and arrays programmatically, making it ideal for use cases such as building REST API responses or handling configuration files. Furthermore, the choice between .get() and .path() methods ensures safer and more robust handling of potentially missing fields in JSON data.
In summary, when dealing with unpredictable or frequently changing JSON structures, leveraging the Tree Model approach offers maximum flexibility, reduces boilerplate code, and improves the maintainability of your Java applications. Always prefer path() over get() in uncertain scenarios to avoid NullPointerException and ensure more stable code execution.
When working with JSON data in real-world applications, it is very common to deal with collections, especially lists of objects. Jackson provides easy and powerful mechanisms to handle JSON arrays and convert them into Java collections, such as List<User>.
1. What Is Collection Handling?
Collection handling refers to the process of deserializing a JSON array into a Java collection (usually a List, Set, or Map) of objects, and serializing a Java collection back into a JSON array.
2. Why Is This Important?
API responses often return lists of items (e.g., list of users, orders, products).
Data persistence can involve storing or reading multiple records in a structured JSON array format.
public class User {
private String name;
private int age;
public User() { }
public User(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
}
4.1. Deserialize JSON Array into List<User>
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.List;
public class JacksonCollectionDeserializationExample {
public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
// Read JSON array from file
File jsonFile = new File("users.json");
// Deserialize JSON array into List<User>
List < User > users = objectMapper.readValue(jsonFile, new TypeReference < List < User >> () {});
// Iterate over users
for (User user: users) {
System.out.println("Name: " + user.getName() + ", Age: " + user.getAge());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
➤ Explanation of Key Concepts:
new TypeReference<List<User>>() {} is necessary because of Java’s type erasure: It tells Jackson the full generic type to deserialize into, since List<User> cannot be determined at runtime without help.
The JSON file (users.json) contains an array of user objects.
would return a List<Map<String, Object>> instead of List<User>.
By using:
new TypeReference<List<User>>() {}
Jackson understands the correct mapping.
6. When to Use Collection Handling
Scenario
Use Case
API returns a list of entities
Deserialize JSON array into List<User>
Bulk data persistence
Serialize List<User> into JSON array in a file
Data transformation
Map JSON array to Java collection, then manipulate data
✅ Conclusion
Handling collections is a critical aspect of real-world JSON processing. Jackson’s combination of TypeReference, ObjectMapper.readValue(), and writeValue() makes it effortless to convert JSON arrays into Java collections and back. This ensures efficient, type-safe handling of structured batch data from APIs, configuration files, or persistent storage.