0

I want to achieve the below snippet using java 8 streams.Any answers would be appreciable.I need to set different values for the same key 'amount'.so that i am creating new hashmap inside a loop.It will be like [{amount=100},{amount=200}].

List<String> data = Arrays.asList('', '', '');
List<Map<String,Object> finalList = new ArrayList();
for(String dataIterate : data) {
    Map<String,Object> map = new HashMap();
    map.put("amount",dataIterate);
    finalList.add(map);
}
RathanaKumar
  • 325
  • 4
  • 14

3 Answers3

2

Is that what you are asking for,

List<Map<String, String>> result = data.stream()
        .map(s -> Stream.of(s).collect(Collectors.toMap(s2 -> "amount", Function.identity())))
        .collect(Collectors.toList());

Get each element in the source, create a Map with the given constant key and that elements value. Finally collect them into a List

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
2
 data.stream()
     .map(dataIterate -> {
           Map<String,Object> map = new HashMap();
           map.put("amount", dataIterate);
           return map;
     })
     .collect(Collectors.toList()) // or any other terminal operation you might need

But it's really unclear why not a simpler SimpleEntry or Pair, or anything else that can hold a key/value instead of a Map with a single Entry

Eugene
  • 117,005
  • 15
  • 201
  • 306
0

You can do as follow, using initialization block for the Map :

List<Map<String, String>> map = 
           data.stream().map(data -> new HashMap<String, String>(){{put("amount", data);}})
                        .collect(Collectors.toList());

Workable Demo


But to store multiples values for the same keys, you'd better use a Map<String, List<String>>

azro
  • 53,056
  • 7
  • 34
  • 70
  • This is prone to memory leaks, as this subclass of `HashMap` will keep a reference to `data` even if you remove the entry, as well as a reference to the outer instance if you use this in a non-static context. – Holger Jul 12 '18 at 11:21
  • @Holger nore sure to understand, how it is so different of what you proposed as comment below ? – azro Jul 12 '18 at 11:22
  • The curly braces create an anonymous inner class subclassing `HashMap` and capturing the variables used inside the body (i.e. `data`). Further, unlike lambda expressions, anonymous inner classes always capture a reference to the outer `this`, even if it’s not used. This is entirely different to performing a method invocation to `Collections.singletonMap("amount", dataIterate)` which will just return an instance of a map containing the specified mapping. See also [What is Double Brace initialization in Java?](https://stackoverflow.com/a/27521360/2711488)… – Holger Jul 12 '18 at 11:27
  • Thank u @azro.This is the thing i expected. – RathanaKumar Jul 12 '18 at 13:35