2

I need to store all keys into single string variable each key separated by a comma and also I need to do the same for all values

Here is my code

HashMap<String, Object> yourHashMap = new Gson().fromJson(dynamicJson, HashMap.class);
    
yourHashMap.forEach((k, v) -> {
    //System.out.println("Key: " + k );
    String result = k + ",";
    System.out.println("Keys : "+result);
});

Actual output Keys : name, message,

Expected output : Keys : name, message

Values : "Message1", "Message Content"

Using these outputs I'm going to create CSV file it uses keys as header and values as rows

3 Answers 3

3

You can use Collectors.joining() to add comma separation

String keys = map.keySet().stream().collect(Collectors.joining(", "));
String values = map.values().stream().map(obj -> String.valueOf(obj)).collect(Collectors.joining(", "));

, main function

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "val1");
        map.put("key2", "val2");
        map.put("key3", "val3");
        map.put("key4", "val4");
        String keys = map.keySet().stream().collect(Collectors.joining(", "));
        String values = map.values().stream().map(obj -> String.valueOf(obj)).collect(Collectors.joining(", "));
        System.out.println("Keys: " + keys);
        System.out.println("Values: " + values);
    }

, output

Keys: key1, key2, key3, key4
Values: val1, val2, val3, val4
Sign up to request clarification or add additional context in comments.

2 Comments

If the values are Object then a .map with the cast to String is needed: .map(value -> (String) value)
Yes, you are right. I have updated it :D thank you :)
1
    HashMap<String, Object> yourHashMap = new Gson().fromJson(dynamicJson, HashMap.class);
    LinnkedHashSet<String> keys = new LinnkedHashSet<>();
    LinnkedHashSet<String> values = new LinnkedHashSet<>();
    yourHashMap.forEach((k, v) -> {
            keys.add(k);
            values.add(v);
       });
    System.out.println("keys: "+String.join(",",keys) +
                       "\n values: "+ String.join(",",values));

Comments

1

Use String.join

HashMap<String, String> yourHashMap = ....
String keys = String.join(",", yourHashMap.keySet());
String values = String.join(",", yourHashMap.values());

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.