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
8
  • 1
    Ok and what are you stuck on? Did you read the Stream tutorial? docs.oracle.com/javase/tutorial/collections/streams Commented Aug 5, 2016 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? Commented Aug 5, 2016 at 17:42
  • Can you post what you have then? Commented Aug 5, 2016 at 17:43
  • I have the same solution as.. stackoverflow.com/questions/22933296/… Commented Aug 5, 2016 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. Commented Aug 5, 2016 at 17:45

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.