Sallyerik
Sallyerik

Reputation: 519

How can I merge two List<String> into a single List<String>?

I've saw some others questions about the same thing, but any of them fix my problem. Could be because I dont get the concept of it.

I have two List<String>:

List<String> PlatformInfo1 = new ArrayList
List<String> PlatformInfo2 = new ArrayList

Those List content some info from my database:

PlatformInfo1= [{"Nnodes":"163"}]
PlatformInfo2= [{"Commnet":"Windows Machine"}]

In order to interact with each element, I trying to include both array in one single object List<String> :

List<String> PlatformInfoGI = new ArrayList<String>();
PlatformInfoGI.addAll(PlatformInfo1);
PlatformInfoGI.addAll(PlatformInfo2);

The result which I'm getting is:

Value of PlatformInfoGI: [{"Nnodes":"163"},{"Commnet":"Windows Machine"}]

It would possible to do something to transform those List<String> into something like that:

 Value of PlatformInfoGI: [{"Nnodes":"163","Commnet":"Windows Machine"}]

NOTE the missing braces between elements.

What I wanted to get is a List<String> with one single element and different properties (Strings)

Upvotes: 0

Views: 107

Answers (3)

Chris
Chris

Reputation: 1

I don't think there is case to show the result as: Value of PlatformInfoGI: [{"Nnodes":"163"},{"Commnet":"Windows Machine"}]

for such result, it is a list contains 2 objects, while you had defined the list as : **List<String>** PlatformInfoGI = new **ArrayList<String>**(); PlatformInfoGI.addAll(PlatformInfo1); PlatformInfoGI.addAll(PlatformInfo2);

could should show me the result in your console by the sample code ?

Upvotes: 0

Viki Cullen
Viki Cullen

Reputation: 82

Am modifying slightly ,

List PlatformInfo1 = new ArrayList();

List PlatformInfo2 = new ArrayList();

    PlatformInfo1.add("Nnodes");
    PlatformInfo1.add("163");

    PlatformInfo2.add("Commnet");
    PlatformInfo2.add("Windows Machine");

    List<String> PlatformInfoGI = new ArrayList<String>();
    PlatformInfoGI.addAll(PlatformInfo1);
    PlatformInfoGI.addAll(PlatformInfo2);

    System.out.println(PlatformInfoGI);

This will print the result as : [Nnodes, 163, Commnet, Windows Machine]

P.S : May i know which IDE you are using ?

Upvotes: 0

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

Use apache commons collections' ListUtils.union(java.util.List list1, java.util.List list2)

Returns a new list containing the second list appended to the first list. The List.addAll(Collection) operation is used to append the two given lists into a new list.

Upvotes: 1

Related Questions