Convert each list to map and merge it (I use Lombok to not write boilerplate code):

@Data
@NoArgsConstructor
@AllArgsConstructor
class Server {
    private String name;
    private String attribute1;
    private String attribute2;
}

public class ServerMain {

    public static void main(String[] args) {

        List<Server> servers1 = Arrays.asList(
                new Server("name1", "attr1.1", null),
                new Server("name2", "attr1.2", null));

        List<Server> servers2 = Arrays.asList(
                new Server("name1", null, "attr2.1"),
                new Server("name2", null, "attr2.2"));

        Map<String, Server> serverMap1 = servers1.stream().collect(Collectors.toMap(Server::getName, Function.identity()));
        Map<String, Server> serverMap2 = servers2.stream().collect(Collectors.toMap(Server::getName, Function.identity()));

        serverMap1.keySet().forEach(key -> serverMap1.merge(key,
                serverMap2.get(key),
                (server1, server2) -> {
                    server1.setAttribute2(server2.getAttribute2());
                    return server1;
                }));


        System.out.println(serverMap1);
    }
}
Answer from Dmitry Gorkovets on Stack Overflow
Top answer
1 of 3
4

Convert each list to map and merge it (I use Lombok to not write boilerplate code):

@Data
@NoArgsConstructor
@AllArgsConstructor
class Server {
    private String name;
    private String attribute1;
    private String attribute2;
}

public class ServerMain {

    public static void main(String[] args) {

        List<Server> servers1 = Arrays.asList(
                new Server("name1", "attr1.1", null),
                new Server("name2", "attr1.2", null));

        List<Server> servers2 = Arrays.asList(
                new Server("name1", null, "attr2.1"),
                new Server("name2", null, "attr2.2"));

        Map<String, Server> serverMap1 = servers1.stream().collect(Collectors.toMap(Server::getName, Function.identity()));
        Map<String, Server> serverMap2 = servers2.stream().collect(Collectors.toMap(Server::getName, Function.identity()));

        serverMap1.keySet().forEach(key -> serverMap1.merge(key,
                serverMap2.get(key),
                (server1, server2) -> {
                    server1.setAttribute2(server2.getAttribute2());
                    return server1;
                }));


        System.out.println(serverMap1);
    }
}
2 of 3
2

For each server in servers1 find a matching server2 in servers2 and set the missing attribute of the first one to correct attribute else if there is no matching server by name simply return null. Also note that this implementation will return only the list of servers name contained in servers1.

@AllArgsConstructor
@Data
private class Server {
   private String name;
   private String attribute1;
   private String attribute2;
}

List<Server> completServersInfo = servers1.stream()
     .map((server1 -> {
        Server matchingServer = servers2.stream()
           .filter(server2 -> server2.name.equals(server1.name))
           .findFirst()
           .orElse(null);
        server1.setAttribute2(matchingServer.attribute2);
        return server1;
     }))
     .collect(Collectors.toList());
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ merge-two-lists-objects-key-java-8
How to Merge Two Lists of Objects by Key in Java 8 - CodingTechRoom
This method allows for the combination of distinct objects based on a common property or key, facilitating data consolidation and aggregation. For a broader Java reference, Java: The Complete Reference, Twelfth Edition is a useful companion. ... import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class MergeLists { public static void main(String[] args) { List<Object1> list1 = new ArrayList<>(); List<Object2> list2 = new ArrayList<>(); // Suppose Object1 and Object2 have a common field called 'id' List<MergedObject> mergedList = list1.stream() .collect(Collectors.toMap(Object1::getId, Function.identity(), MergeLists::mergeValues)) .values() .stream() .collect(Collectors.toList()); } private static MergedObject mergeValues(Object1 obj1, Object1 obj2) { // Logic to merge obj1 and obj2 } }
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2013 โ€บ 08 โ€บ -example-to-merge-or-join-multiple-List-in-Java.html
2 Example to Merge or Join Multiple List in Java - Tutorial
There are two main ways to merge, join or combine two List in Java, by using addAll(Collection c) method or by using ListUtils union method from Apache commons Collection. In this Java tutorial, we will see examples of both approaches.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ merge-two-lists-in-java
How to Merge Two Lists in Java? | DigitalOcean
Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ -merge-two-lists-common-key-java
How to Merge Two Lists by a Common Key in Java? - CodingTechRoom
Merging two lists based on a common key involves finding the key present in both lists and consolidating the related data into a new combined structure. In Java, this is often done using streams, maps, or traditional loops.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ java map โ€บ combining two lists into a map in java
Combining Two Lists Into a Map in Java | Baeldung
June 27, 2025 - We then iterate through each element in KEY_LIST using a for loop, and for each element, we retrieve the corresponding element from VALUE_LIST using the same index i. Then, the put() method fills the key-value pair into the result map. Stream API provides many concise and efficient ways to manipulate Java collections. So next, letโ€™s use the Java Stream API to associate two lists:
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-combine-two-list-by-alternatively-taking-elements
Java Program to Combine Two List by Alternatively Taking Elements - GeeksforGeeks
August 8, 2022 - A loop is then used to iterate over the remaining elements of the longer list and store them at the end one by one. The data type of the merged list should be similar to the individual lists. Implementation: Two examples are discussed below considering both integer list and string lists ... // Java Program to Combine Two List // by Alternatingly Taking Elements // importing required packages import java.io.*; import java.util.*; import java.util.Iterator; // Class to access alternate elements class GFG { // Main driver method public static void main(String[] args) { // Creating(declaring) list
๐ŸŒ
Quora
quora.com โ€บ How-can-two-lists-be-merged-into-one-list-in-Java
How can two lists be merged into one list in Java? - Quora
Answer (1 of 2): Assuming you don't want to modify any of the existing lists(firstList and secondList), Here's one way [code] List newList = new ArrayList (firstList); //create a new list of firstList newList.addAll(secondList); //add the secondList contents to firstList.[/code] H...
Top answer
1 of 1
1

You will need to make use of Google's gson library to parse your json Strings and also create Additional Classes to hold the data for the same. Save your json String in Files to read the content and convert them to appropriate Objects.

The JSON Strings you have mentioned have error since you are using (โ€œ) at many places. Replace them with (") at all locations. This change is very important because if you don't do it you might get Exceptions or undesirable outputs.

Store your Json strings as follows:

List1.txt

{
"One": [
    "G13DA"
],
"Two": [
    "G13AA",
    "G13AD"
]
}

List2.txt

[
{
    "subgroupCode": "G13AA",
    "productGroup": [
        {
            "productCode": "G1A",
            "productDescription": "Two 1"
        },
        {
            "productCode": "G9B",
            "productDescription": "Two 2"
        }
    ]
},
{
    "subgroupCode": "G13AD",
    "productGroup": [
        {
            "productCode": "G4A",
            "productDescription": "Two 3"
        },
        {
            "productCode": "G9C",
            "productDescription": "Two 4"
        }
    ]
},
{
    "subgroupCode": "G13DA",
    "productGroup": [
        {
            "productCode": "G5M",
            "productDescription": "One 1"
        },
        {
            "productCode": "G9M",
            "productDescription": "One 2"
        }
    ]
}
]

You will need to change the file paths of these two while Running the Program

Add the following classes

JuniorArea.class

public class JuniorArea {
    private String juniorAreaDescription;
    private List<MerchandisingGroup> mechandisingGroup;

    public String getJuniorAreaDescription() {
        return juniorAreaDescription;
    }
    public void setJuniorAreaDescription(String juniorAreaDescription) {
        this.juniorAreaDescription = juniorAreaDescription;
    }
    public List<MerchandisingGroup> getMechandisingGroup() {
        return mechandisingGroup;
    }
    public void setMechandisingGroup(List<MerchandisingGroup> mechandisingGroup) {
        this.mechandisingGroup = mechandisingGroup;
    }

    @Override
    public String toString() {
        return "JuniorArea [juniorAreaDescription=" + juniorAreaDescription + ", mechandisingGroup=" + mechandisingGroup
                + "]";
    }
} 

JuniorAreaCollection.class

public class JuniorAreaCollection {
    private List<JuniorArea> juniorArea;

    public List<JuniorArea> getJuniorArea() {
        return juniorArea;
    }

    public void setJuniorArea(List<JuniorArea> juniorArea) {
        this.juniorArea = juniorArea;
    }

    @Override
    public String toString() {
        return "JuniorAreaCollection [juniorArea=" + juniorArea + "]";
    }
}

MerchandisingGroup.class

public class MerchandisingGroup {
    private String productCode;
    private String productDescription;

    public String getProductCode() {
        return productCode;
    }
    public void setProductCode(String productCode) {
        this.productCode = productCode;
    }
    public String getProductDescription() {
        return productDescription;
    }
    public void setProductDescription(String productDescription) {
        this.productDescription = productDescription;
    }

    @Override
    public String toString() {
        return "MechandisingGroup [productCode=" + productCode + ", productDescription=" + productDescription + "]";
    }
}

Product.class

public class Product {
    private String subgroupCode;
    private List<ProductGroup> productGroup;

    public String getSubgroupCode() {
        return subgroupCode;
    }
    public void setSubgroupCode(String subgroupCode) {
        this.subgroupCode = subgroupCode;
    }
    public List<ProductGroup> getProductGroup() {
        return productGroup;
    }
    public void setProductGroup(List<ProductGroup> productGroup) {
        this.productGroup = productGroup;
    }

    @Override
    public String toString() {
        return "Product [subgroupCode=" + subgroupCode + ", productGroup=" + productGroup + "]";
    }
}

ProductGroup.class

public class ProductGroup {
    private String productCode;
    private String productDescription;

    public String getProductCode() {
        return productCode;
    }
    public void setProductCode(String productCode) {
        this.productCode = productCode;
    }
    public String getProductDescription() {
        return productDescription;
    }
    public void setProductDescription(String productDescription) {
        this.productDescription = productDescription;
    }

    @Override
    public String toString() {
        return "ProductGroup [productCode=" + productCode + ", productDescription=" + productDescription + "]";
    }
}

Finally run the follwing Main Class code, to check the output

public class MainRunner {
    // Use Path according to your file system
    private static String List1Path = "/List1.txt";

    // Use Path according to your file system
    private static String List2Path = "/List2.txt";

    public static void main(String...arg) throws UnsupportedEncodingException, IOException {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        String List1Content = new String(Files.readAllBytes(Paths.get(List1Path)), "UTF-8");

        Map<String, List<String>> map = new HashMap<>();

        map = gson.fromJson(List1Content, new TypeToken<Map<String, List<String>>>() {}.getType());

        System.out.println(map);

        String List2Content = new String(Files.readAllBytes(Paths.get(List2Path)), "UTF-8");

        List<Product> products = gson.fromJson(List2Content, new TypeToken<List<Product>>() {}.getType());

        System.out.println(products);

        List<JuniorArea> juniorAreas = new ArrayList<>();

        for (String s : map.keySet()) {
            JuniorArea juniorArea = new JuniorArea();

            juniorArea.setJuniorAreaDescription(s);

            List<MerchandisingGroup> merchandisingGroups = new ArrayList<>();

            List<String> subgroupCodes = map.get(s);

            for (String subgroupCode : subgroupCodes) {

                for (Product product : products) {

                    if (product.getSubgroupCode().equals(subgroupCode)) {
                        List<ProductGroup> productGroups = product.getProductGroup();

                        for (ProductGroup productGroup : productGroups) {
                            MerchandisingGroup merchandisingGroup = new MerchandisingGroup();

                            merchandisingGroup.setProductCode(productGroup.getProductCode());
                            merchandisingGroup.setProductDescription(productGroup.getProductDescription());

                            merchandisingGroups.add(merchandisingGroup);
                        }
                    }

                }

            }

            juniorArea.setMechandisingGroup(merchandisingGroups);

            juniorAreas.add(juniorArea);
        }

        JuniorAreaCollection collection = new JuniorAreaCollection();

        collection.setJuniorArea(juniorAreas);

        System.out.println(gson.toJson(collection));
    }
}

Output should be printed on your console

{
  "juniorArea": [
    {
      "juniorAreaDescription": "One",
      "mechandisingGroup": [
        {
          "productCode": "G5M",
          "productDescription": "One 1"
        },
        {
          "productCode": "G9M",
          "productDescription": "One 2"
        }
      ]
    },
    {
      "juniorAreaDescription": "Two",
      "mechandisingGroup": [
        {
          "productCode": "G1A",
          "productDescription": "Two 1"
        },
        {
          "productCode": "G9B",
          "productDescription": "Two 2"
        },
        {
          "productCode": "G4A",
          "productDescription": "Two 3"
        },
        {
          "productCode": "G9C",
          "productDescription": "Two 4"
        }
      ]
    }
  ]
}
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-merge-two-lists-in-java
How to merge two lists in Java
We will create an empty list and then we will add all the elements of both the given lists to the new list with this method. The addAll() method takes the specified elements as parameters. We will pass both the given lists as a parameter one by one.
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ collections framework โ€บ java arraylist โ€บ how to merge two arraylists in java
How to Merge Two ArrayLists in Java
January 19, 2023 - To get a merged list minus duplicate elements, we have two approaches: The Java Sets allow only unique elements. When we push both lists in a Set and the Set will represent a list of all unique elements combined.
๐ŸŒ
Techie Delight
techiedelight.com โ€บ home โ€บ java โ€บ join two lists in java
Join two lists in Java | Techie Delight
July 7, 2026 - This post will discuss how to join two Java lists using Plain Java, Java 8, Guava, and Apache Commons Collections. ... List interface provides the addAll(Collection) method that appends all elements of the specified collection at the end of the list. We can use it as follows: We can also initialize the result list by the first list using the ArrayList constructor, thereby preventing an extra call to addAll().
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ java program to merge two lists
Java Program to Merge Two Lists | Scaler Topics
June 9, 2024 - addAll() method to merge two lists in Java to add all the members of the specified list in the same order as the original list by passing the name of the list as an argument.
๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ java โ€บ programs โ€บ merge-two-lists
How to Merge Two Lists in Java? (5 Programs)
October 17, 2025 - Learn how to merge two lists in Java with 5 different programs. Explore methods using addAll(), Java Stream, for-loops, and more with clear examples.
๐ŸŒ
Javaprogramto
javaprogramto.com โ€บ 2020 โ€บ 11 โ€บ java-join-two-lists.html
How To Join Two Or Combine More Lists In old and new Java 8 Steam API? JavaProgramTo.com
November 15, 2020 - Apache commons api has a ListUtils class with union() method which takes two list objects and returns the merged list.
Top answer
1 of 2
1

If you are using Jackson (one of the most popular JSON libraries), you can simply achieve this as follows:

Code Snippet

ObjectMapper mepper = new ObjectMapper();
List<Map<String, Object>> listAs400 = mepper.readValue(jsonStrAs400, List.class);
List<Map<String, Object>> listSqlServer = mepper.readValue(jsonStrSqlServer, List.class);
listAs400.forEach(e1 -> {
    listSqlServer.forEach(e2 -> {
        if (e1.get("truckNumber").toString().equals(e2.get("truckNumber").toString())) {
            e2.forEach((k, v) -> {
                e1.put(k, v);
            });
        }
    });
});
System.out.println(mapper.writeValueAsString(listAs400));

Console Output

[ 
  { 
    "assetId":308,
    "type":"OV",
    "truckNumber":"L122",
    "longitude":0,
    "latitude":0,
    "id":308,
    "trailerGroup":"C",
    "loaded":false,
    "dedicated":false,
    "intermodal":false,
    "sealed":false,
    "companyOwned":true,
    "onSite":false,
    "customerId":"KTPH",
    "modified":{ 
      "when":1546498401156
    },
    "created":{ 
      "when":1546498401156
    }
  },
  { 
    "assetId":309,
    "type":"PO",
    "truckNumber":"SQ46",
    "longitude":0,
    "latitude":0,
    "id":309,
    "trailerGroup":"C",
    "loaded":false,
    "dedicated":false,
    "intermodal":false,
    "sealed":false,
    "companyOwned":true,
    "onSite":true,
    "customerId":"KTPH",
    "modified":{ 
      "when":1546498401156
    },
    "created":{ 
      "when":1546498401156
    }
  }
]
2 of 2
0

Try the example below. I believe this fulfills your requirements of merging your two lists, updating any existing values and finally adding any that are not in the first query.

In addition, I took into consideration that you are using Java Runtime Environment 7(JRE 1.7).

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class App {

    private static String path1 = "C:\\path\\to\\AS400.json";
    private static String path2 = "C:\\path\\to\\SQL_Server_query.json";

    public static void main( String[] args ) {
        JSONArray trailersAS400 = null;
        JSONArray trailersSQLServer = null;
        try {
            FileReader fr = new FileReader(path1);
            FileReader fr2 = new FileReader(path2);
            // utilize simple json parser to parse json objects
            trailersAS400 = (JSONArray) new JSONParser().parse(fr);
            trailersSQLServer = (JSONArray) new JSONParser().parse(fr2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Object> list = new ArrayList<Object>(); // store parsed JSON's data in a list
        for (Object trSQL : trailersAS400) {
            list.add(trSQL);
        }
        for (Object tr400 : trailersSQLServer) {
            list.add(tr400);
        }

        HashMap<String, Object> map1 = new HashMap<String, Object>(); // maps truck L122 key value pairs
        HashMap<String, Object> map2 = new HashMap<String, Object>(); // maps truck SQ46 key value pairs
        for (Iterator iter = list.iterator(); iter.hasNext();) { // iterate through list and update map1 with key value pair.
            HashMap<String, Object> truck = (HashMap<String, Object>) iter.next();
            if (truck.containsValue("L122")) {
                Set<Entry<String, Object>> s = truck.entrySet();
                for (Entry<String, Object> entry : s) {
                    map1.put(entry.getKey(), entry.getValue());
                }
            } else if (truck.containsValue("SQ46")) { // iterate through list and update map2 with key value pair.
                Set<Entry<String, Object>> s = truck.entrySet();
                for (Entry<String, Object> entry : s) {
                    map2.put(entry.getKey(), entry.getValue());
                }
            }
        }
        // Update map with map1 & map2. Note the key is represented as the truck number.
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("L122", map1);
        map.put("SQ46", map2);
        Gson pp = new GsonBuilder().setPrettyPrinting().create();
        String p = pp.toJson(map);
        System.out.println(p);
    }
}

output:

{
  "L122": {
    "truckNumber": "L122",
    "dedicated": false,
    "sealed": false,
    "created": {
      "when": 1546498401156
    },
    "latitude": 0,
    "type": "OV",
    "loaded": false,
    "intermodal": false,
    "companyOwned": true,
    "assetId": 308,
    "customerId": "KTPH",
    "onSite": false,
    "modified": {
      "when": 1546498401156
    },
    "trailerGroup": "C",
    "id": 308,
    "longitude": 0
  },
  "SQ46": {
    "truckNumber": "SQ46",
    "dedicated": false,
    "sealed": false,
    "created": {
      "when": 1546498401156
    },
    "latitude": 0,
    "type": "PO",
    "loaded": false,
    "intermodal": false,
    "companyOwned": true,
    "assetId": 309,
    "customerId": "KTPH",
    "onSite": true,
    "modified": {
      "when": 1546498401156
    },
    "trailerGroup": "C",
    "id": 309,
    "longitude": 0
  }
}

For the purpose of performance. You may consider using a LinkedHashMap versus a HashMap as is done in the example above. Iterating is more efficient when using a LinkedHashMap. The below example uses this approach.

public class App {

private static String path1 = "C:\\path\\to\\AS400.json";
private static String path2 = "C:\\path\\to\\SQL_Server_query.json";


    public static void main( String[] args ) {
        JSONArray trailersAS400 = null;
        JSONArray trailersSQLServer = null;
        try {
            FileReader fr = new FileReader(path1);
            FileReader fr2 = new FileReader(path2);
            // utilize simple json parser to parse json objects
            trailersAS400 = (JSONArray) new JSONParser().parse(fr);
            trailersSQLServer = (JSONArray) new JSONParser().parse(fr2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Object> list = new ArrayList<Object>(); // store parsed JSON's data in a list
        for (Object trSQL : trailersAS400) {
            list.add(trSQL);
        }
        for (Object tr400 : trailersSQLServer) {
            list.add(tr400);
        }

        HashMap<String, Object> map1 = new HashMap<String, Object>(); // maps truck L122 key value pairs
        HashMap<String, Object> map2 = new HashMap<String, Object>(); // maps truck SQ46 key value pairs
        Iterator<Object> iter = list.iterator();
        while (iter.hasNext()) { // iterate through list and update map1 with key value pair.
            LinkedHashMap<String, Object> truck = new LinkedHashMap<String, Object>(); 
            truck.putAll((Map<? extends String, ? extends Object>) iter.next());
            if (truck.containsValue("L122")) {
                Set<Entry<String, Object>> s = truck.entrySet();
                for (Entry<String, Object> entry : s) {
                    map1.put(entry.getKey(), entry.getValue());
                }
            } else if (truck.containsValue("SQ46")) { // iterate through list and update map2 with key value pair.
                Set<Entry<String, Object>> s = truck.entrySet();
                for (Entry<String, Object> entry : s) {
                    map2.put(entry.getKey(), entry.getValue());
                }
            }
        }
        // Update map with map1 & map2. Note the key is represented as the truck number.
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("L122", map1);
        map.put("SQ46", map2);
        Gson pp = new GsonBuilder().setPrettyPrinting().create();
        String p = pp.toJson(map);
        System.out.println(p);
    }
}

Both example code will produce your desired results as indicted in the above output.

๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ java โ€“ combine multiple collections
Java - Combine Multiple Collections | Baeldung
May 11, 2024 - Initially, you get a Stream whose elements are the two collections, and then you flatten the Stream before collecting it into a merged list: Stream<String> combinedStream = Stream.of(collectionA, collectionB) .flatMap(Collection::stream); Collection<String> collectionCombined = combinedStream.collect(Collectors.toList()); The Guava library from Google provides several convenience methods for operating on collections and can be used with Java 6 or later.