Farrukh Chishti
Farrukh Chishti

Reputation: 8437

Create list of map using streams and lambda expressions

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

Upvotes: 0

Views: 2208

Answers (2)

Flown
Flown

Reputation: 11740

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());

Upvotes: 4

vaski thakur
vaski thakur

Reputation: 92

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));

Upvotes: 0

Related Questions