[英]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.我有一个字符串,它是逗号分隔的键值对,其中键是唯一的,并且不会多次存在,我想将字符串拆分为仅基于一个键“s”的键值过滤,并为其返回 output在本例中为“GRADE3”。
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.我想在 Java 8 中拆分上面的字符串,并只读键“s”的值为“03”,并在内部从下面的 HashMap 读取其值,所以基本上我想在本例中为 03 返回字符串“GRADE3”。
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?任何人都可以使用流在 Java 8 中提供帮助吗?
You can split the string and filter over its stream.您可以拆分字符串并过滤其 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);
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: Output:
GRADE3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.