0

I tried to find a way to convert Map<String,String> into String[] using Java 8 way.

A Map

{"A":"a", "B","b", "C", "c"}` 

should be converted to

["A", "a", "B", "b", "C", "c"] or ["B", "b", "C", "c", "A", "a"] ...

The order of the pairs does not matter but key/value pairs must be together.

The old way to do this is obvious:

Map<String, String> headers = .......
String[] array = new String[headers.size() * 2];
int i = 0;
for(Map.Entry<String, String> entry : headers.entrySet()) {
    array[i++] = entry.getKey();
    array[i++] = entry.getValue();
}
3
  • what have you tried? look into the direction of creating a stream of entrySet Commented Jun 18, 2021 at 22:16
  • You can also do headers.forEach((k, v) -> { array[i++] = k; array[i++] = v; }); Commented Jun 18, 2021 at 23:39
  • Or with StreamEx: EntryStream.of(headers).flatMapKeyValue(Stream::of).toArray(String[]::new) Commented Jun 18, 2021 at 23:48

1 Answer 1

7
import java.util.Map;
import java.util.Arrays;
import java.util.HashMap;
import java.util.stream.Stream;

class Main {
    private static String[] transform(Map<String, String> map) {
        return map.entrySet().stream()
            .flatMap(entry -> Stream.of(entry.getKey(), entry.getValue()))
            .toArray(String[]::new);
    } 
    
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("A", "a");
        map.put("B", "b");
        map.put("C", "c");
        
        String[] result = transform(map);

        System.out.println(Arrays.toString(result));
        // Output: [A, a, B, b, C, c]
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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