0

Not sure about the best way to get this List in below format. Please suggest better way to get this format in Java. And also below list is dynamic. Sometimes the values can go up to 10 or more

List<String> list = Arrays.asList("ABC", "DEF", "GHI");

Now we want the above list to be printed as below -

[{"key" : "ABC"}, {"key" : "DEF"}, {"key" : "GHI"}]

I tried to use MultiMap like below

Multimap<String, String> multimap = ArrayListMultimap.create();

multimap.put("key", "ABC");
multimap.put("key", "DEF");
multimap.put("key", "GHI");

Which prints values like

{key=[ABC, DEF, GHI]}
Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49
hdevi
  • 17
  • 3
  • In a map, keys can't be duplicated. Keys should be unique. – Govinda Sakhare Jan 19 '20 at 05:40
  • Yes. I used MultiMap not Map. if you have any other sugesstion, you are welcome. Thank you. – hdevi Jan 19 '20 at 05:45
  • 1
    Are you willing to convert this list to json? – Abdul Alim Shakir Jan 19 '20 at 05:48
  • @AbdulAlimShakir if that makes job simple, please suggest – hdevi Jan 19 '20 at 05:50
  • 1
    If it's just a question of *printing* the way you showed, then you can try `System.out.println(multimap.entries().stream().map(e -> String.format("{\"%s\": \"%s\"}", e.getKey(), e.getValue())).collect(Collectors.toList()));` – ernest_k Jan 19 '20 at 05:52
  • @ernest_k This looks great. In this case, Can I also Just format the List instead of going for MultiMap again ? I mean the List list = Arrays.asList("ABC", "DEF", "GHI"); as in the same format with 'Key' as same for the values in the list – hdevi Jan 19 '20 at 05:56
  • Will it always be the same key for each element of the list (such that you can hard-code it there)? – ernest_k Jan 19 '20 at 05:58
  • @ernest_k Yes. the Key value is same. Hardcoding is also fine. But in the above example, you are using map. Can we just use for List and get the same format ? – hdevi Jan 19 '20 at 05:59
  • 1
    Sure, you can `list.stream().map(e -> String.format("{\"key\" : \"%s\"}", e)).collect(Collectors.toList())` – ernest_k Jan 19 '20 at 06:02
  • @ernest_k I see an error as 'Incompatible types. Required String but, 'collect' was inferred to R: no instance(s) of type variables(s) T exits so that List confirms to String.' – hdevi Jan 19 '20 at 06:12
  • @hdevi `list.stream().map(e -> String.format("{\"key\" : \"%s\"}", e)).collect(Collectors.toList()).toString(); ` You need to convert it to `String` using `toString()` – Govinda Sakhare Jan 19 '20 at 06:35

2 Answers2

1

You can access underlying entries structure multimap.entries() and format the string as per the need.

multimap.entries().stream()
      .map(entry -> String.format("{\"%s\": \"%s\"}", entry.getKey(), entry.getValue()))
      .collect(Collectors.toList()));

ernest_k has already provided a couple of nice ways to get the desired string in the comment section. You can extend those solutions by writing a custom class that can take a key.

List<String> list = Arrays.asList("ABC", "DEF", "GHI");
MapKeyToValues keyValues = new MapKeyToValues("key", list); // change key as per your need
System.out.println(keyValues);
String formattedString = keyValues.toString();

Custom converter class.

public class MapKeyToValues {
    private final String key;
    private final List<String> list;

    public MapKeyToValues(String key, List< String > list) {
        this.key = key;
        this.list = list;
    }

    @Override
    public String toString( ) {
       // need to handle null cases here
       return list.stream()
                .map(value -> String.format("{\"%s\" : \"%s\"}", key, value))
                .collect(Collectors.toList()).toString();
    }
}
Govinda Sakhare
  • 5,009
  • 6
  • 33
  • 74
0

String are immutable. So you have to set again in the list the value. Try this one.

List<String> list = Arrays.asList("ABC", "DEF", "GHI");
for(int i = 0; i < list.size();i++){                  
    list.set(i,"{\"key\" : \""+list.get(i)+"\"}");
}
Abdul Alim Shakir
  • 1,128
  • 13
  • 26