How Do You Deserialize a Collection in Java?

How Do You Deserialize a Collection in Java? A Complete Guide with Code Examples

A Complete Guide with Code Examples

Introduction to Deserialization in Java

Deserialization is the process of converting a byte stream back into an object in Java. It is the opposite of serialization, where an object is converted into a byte stream. Deserialization is commonly used for reading data from files, databases, or network resources. When dealing with collections like Lists, Sets, or Maps, it’s essential to properly deserialize them into their corresponding Java collection types.

In this guide, we will learn how to deserialize collections in Java using different approaches, including using the built-in Java serialization mechanism and popular libraries like Jackson for JSON deserialization.

How Deserialization Works in Java

Java deserialization involves taking a byte stream and converting it back into its original object representation. If you serialize a Java collection like an ArrayList or HashSet, you need to deserialize it back into the collection. Java provides mechanisms like ObjectInputStream for deserialization, but other libraries like Jackson or Gson are often used for more complex data formats like JSON.

Deserializing Collections in Java with Examples

1. Deserializing a List

Let’s start by deserializing a List from a file. In this case, we will use the ObjectInputStream to read an object from a serialized file and deserialize it into a List of String elements.

        
        import java.io.*;
        import java.util.*;

        public class DeserializeListExample {
            public static void main(String[] args) {
                try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("list.dat"))) {
                    List list = (List) in.readObject();
                    System.out.println("Deserialized List: " + list);
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        
        

This example assumes that a List was previously serialized into the list.dat file. When deserializing, we cast the result to List<String> to retrieve the data back in the original type.

2. Deserializing a Set

Now let’s look at how to deserialize a Set. The process is quite similar to deserializing a List, except you use a HashSet or any other Set implementation.

        
        import java.io.*;
        import java.util.*;

        public class DeserializeSetExample {
            public static void main(String[] args) {
                try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("set.dat"))) {
                    Set set = (Set) in.readObject();
                    System.out.println("Deserialized Set: " + set);
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        
        

This example reads from a file called set.dat where the Set was serialized. After reading the object, it is cast to the appropriate type, Set<String>, and printed out.

3. Deserializing a Map

Let’s now look at deserializing a Map, which is a more complex collection type. Here we will deserialize a HashMap containing String keys and Integer values.

        
        import java.io.*;
        import java.util.*;

        public class DeserializeMapExample {
            public static void main(String[] args) {
                try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("map.dat"))) {
                    Map map = (Map) in.readObject();
                    System.out.println("Deserialized Map: " + map);
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        
        

In this case, we are reading a serialized Map object from the map.dat file. The object is cast to Map<String, Integer>, and the deserialized content is printed out to the console.

4. Deserializing JSON into a Collection with Jackson

While the built-in Java serialization mechanism is suitable for many cases, JSON deserialization is often preferred for applications that need to interact with web services or store data in a portable format. Jackson is a popular library for deserializing JSON into Java collections.

Here’s an example of how to use Jackson to deserialize a JSON array into a List.

        
        import com.fasterxml.jackson.databind.ObjectMapper;
        import java.io.*;
        import java.util.*;

        public class DeserializeJsonExample {
            public static void main(String[] args) throws IOException {
                String json = "[\"Apple\", \"Banana\", \"Orange\"]";
                ObjectMapper objectMapper = new ObjectMapper();
                List list = objectMapper.readValue(json, List.class);
                System.out.println("Deserialized List from JSON: " + list);
            }
        }
        
        

In this example, we are using Jackson’s ObjectMapper to deserialize a JSON string into a List<String>. The JSON array is parsed and converted into a list of strings, which is then printed out.

5. Handling Complex Collections

Deserializing complex collections, like a list of maps or sets of lists, requires careful handling of types. Let’s consider deserializing a list of maps:

        
        import com.fasterxml.jackson.core.type.TypeReference;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import java.io.*;
        import java.util.*;

        public class DeserializeComplexCollection {
            public static void main(String[] args) throws IOException {
                String json = "[{\"name\": \"John\", \"age\": 30}, {\"name\": \"Jane\", \"age\": 25}]";
                ObjectMapper objectMapper = new ObjectMapper();
                List> listOfMaps = objectMapper.readValue(json, new TypeReference>>(){});
                System.out.println("Deserialized List of Maps: " + listOfMaps);
            }
        }
        
        

This example shows how to deserialize a complex JSON structure into a List<Map<String, Object>>, which represents a list of maps where each map has string keys and object values.

Conclusion

Deserializing collections in Java is an essential skill for developers working with object serialization or data interchange formats like JSON. Whether you're using the built-in Java ObjectInputStream for binary deserialization or third-party libraries like Jackson for JSON deserialization, understanding how to handle different collection types is critical.

By following the examples in this guide, you can efficiently deserialize collections in your Java applications, ensuring that data is accurately and effectively restored for further processing.

© 2025 Tech Interview Guide. All Rights Reserved.

Please follow and like us:

Leave a Comment