pshud
pshud

Reputation: 13

Parse comma separated key value pairs in stream java 8

I have a string which is comma-separated key-value pairs where keys are unique and it wont exist more than once and I want to split the string into key-value filtering based on just one key “s” and return the output for it as “GRADE3" in this example.

Below is the sample input string

String test = “s:03,g:05,st:06”;

i want to split the above String in Java 8 and read only value of key “s” which is “03” and that internally reads its values from HashMap below, so basically i want to return String “GRADE3" for 03 in this example.

private static final Map<String, String>  STUDENTS_MAP = new HashMap<>();

static {
    STUDENTS_MAP.put(“01”, “GRADE1");
    STUDENTS_MAP.put(“02”, “GRADE2");
    STUDENTS_MAP.put(“03”, “GRADE3");
}

could anyone help this in Java 8 using streams?

Upvotes: 0

Views: 1537

Answers (2)

Unmitigated
Unmitigated

Reputation: 89224

You can split the string and filter over its stream.

String test = "s:03,g:05,st:06";        
String search = "s";

String res = Arrays.stream(test.split(","))
                    .map(s -> s.split(":"))
                    .filter(x -> x[0].equals(search))
                    .findFirst()
                    .map(x -> STUDENTS_MAP.get(x[1]))
                    .orElse(null);

System.out.println(res);

Upvotes: 2

the Hutt
the Hutt

Reputation: 18398

You can try using String split method:

String test = "s:03,g:05,st:06";
String key = test.split(":|,")[1];
String result = STUDENTS_MAP.get(key);
System.out.println(result);

Output:

GRADE3

Upvotes: 0

Related Questions