0

I have an ArrayList of HashMaps in Java and I want to append it to another similar list, Is there any way to do it so that the resulting array list retains the order.

for e.g.:

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

list1.add(hm1);
list1.add(hm2);
list1.add(hm3);

list2.add(hm4);
list2.add(hm5);
list2.add(hm6);

The new List that I want is:

//list 3 = list1 + list2;
list3 = {hm1, hm2, hm3, hm4, hm5, hm6};

How to do that?

Sumit
  • 2,189
  • 7
  • 32
  • 50
  • NB: consider defining interfaces instead of actual classes and using `<>` to auto-infer generic types: `List> list1 = new ArrayList<>();` – Alex Salauyou Oct 21 '15 at 11:36
  • Thanks, for your first point, I have used List and Map interfaces now, but why is it better to auto-infer generic types instead of specifying string when I already know that it is supposed to hold string only? – Sumit Oct 26 '15 at 06:45
  • to make the code less verbose and more readable – Alex Salauyou Oct 26 '15 at 07:00

4 Answers4

5

You can do that easily in Java 8

List<HashMap<String, String>> newList = Stream.concat(listOne.stream(), 
   listTwo.stream()).collect(Collectors.toList());

Or alternatively in Java 7 and lower

List<HashMap<String, String>> newList = new ArrayList<>(list1.size() + list2.size());
newList.addAll(listOne);
newList.addAll(listTwo);

However you should be careful about memory leaks which can be caused by duplicate references to both lists, check out this answer for more info.

Community
  • 1
  • 1
Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
1

Just use List.addAll()) method:

@Test
public void testConcat() {
    List<String> list1 = new ArrayList<String>();
    list1.add("A");
    list1.add("B");
    list1.add("C");

    List<String> list2 = new ArrayList<String>();
    list1.add("D");
    list1.add("E");


    list1.addAll(list2);

    assertThat(list1).containsExactly("A","B","C","D","E");

}
jfcorugedo
  • 9,793
  • 8
  • 39
  • 47
0

You can just do

List<HashMap<String, String>> list3 = new ArrayList<>(list1);
list3.addAll(list2);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
0

Use addAll it used to inserts all of the elements in the specified collection into this list

ArrayList<HashMap<String, String>> list3 = new ArrayList<HashMap<String, String>>();

list3.addAll(list1);
list3.addAll(list2);
karim mohsen
  • 2,164
  • 1
  • 15
  • 19