0
for (String varValue : arrayList1) {
                Map<String, String> mapInstance = new HashMap<>();
                val.put(KEY, VALUE);
                val.put(VAR_KEY, varValue);
                arrayList2.add(mapInstance);
            }

Basically, I want to create a map with two entries and then add each of these maps to a list.

Final list:

{KEY,VALUE}   {VAR_KEY,arrayList1.get(0)}
{KEY,VALUE}   {VAR_KEY,arrayList1.get(1)}
{KEY,VALUE}   {VAR_KEY,arrayList1.get(2)}
...
and so on
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
Farrukh Chishti
  • 7,652
  • 10
  • 36
  • 60
  • 1
    Ok and what are you stuck on? Did you read the Stream tutorial? https://docs.oracle.com/javase/tutorial/collections/streams/ – Tunaki Aug 05 '16 at 17:41
  • Yes. I am able to create the list with map having a only one entry, but how do I create a map with multiple entries? – Farrukh Chishti Aug 05 '16 at 17:42
  • Can you post what you have then? – Tunaki Aug 05 '16 at 17:43
  • I have the same solution as.. http://stackoverflow.com/questions/22933296/using-java8-streams-to-create-a-list-of-objects-from-another – Farrukh Chishti Aug 05 '16 at 17:43
  • Those linked answers do not mention maps. I'm not sure what you're linking me to. But the idea is the same yes: create a Stream from the input list, use `map` to create and return a new `HashMap` and collect into a list. – Tunaki Aug 05 '16 at 17:45
  • I mean just the way he is creating an internal list, I want to create an internal map, BUT with two different rows. – Farrukh Chishti Aug 05 '16 at 17:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/120267/discussion-between-qualtar-demix-and-tunaki). – Farrukh Chishti Aug 05 '16 at 17:48
  • Streams can do this nicely: https://stackoverflow.com/questions/56648200/how-to-create-list-of-maps-from-list-of-object-in-java-without-having-getkey-met – Hephaestus Apr 18 '21 at 01:39

2 Answers2

4

It seems you only need a simple map stage.

List<Map<String, String>> list = arrayList1.stream().map(t -> {
  Map<String, String> map = new HashMap<>();
  map.put("KEY", "VALUE");
  map.put("VAR_KEY", t);
  return map;
}).collect(Collectors.toList());
Flown
  • 11,480
  • 3
  • 45
  • 62
0

What is KEY and VAR_KEY? are they instance variable of some object which you are trying to put in Map from the incoming object.

However, you can try something like this : Map result = arrayList1.stream().collect(Collectors.toMap(Class::getKey, c -> c));

vaski thakur
  • 92
  • 1
  • 9