Collections 使用Java8流将更改应用于映射值

Collections 使用Java8流将更改应用于映射值,collections,filter,java-8,java-stream,Collections,Filter,Java 8,Java Stream,我想使用Java8更改映射值 Map<String, String> attributeMap = new TreeMap<>(); attributeMap.put("C","FIRSTNAMe"); attributeMap.put("C3","1111"); attributeMap.put("C4","ABCNAMe"); 任何人都可以帮助我。您可以创建一个方法转换,并传递一个谓词以确定何时引用或不引用: public static String tranfor

我想使用Java8更改映射值

Map<String, String> attributeMap = new TreeMap<>();
attributeMap.put("C","FIRSTNAMe");
attributeMap.put("C3","1111");
attributeMap.put("C4","ABCNAMe");

任何人都可以帮助我。

您可以创建一个方法
转换
,并传递一个
谓词
以确定何时引用或不引用:

public static String tranform(Map<String, String> attributeMap, Predicate<String> predicate) {
    return attributeMap.entrySet()
            .stream()
            .collect(Collectors.mapping(e -> {
                return e.getKey().toLowerCase() + "=" +
                        (predicate.test(e.getValue()) ? "'" + e.getValue() + "'" : e.getValue());
            }, Collectors.joining(",")));
}
如果只想引用数字,只需使用不同的
谓词

Predicate<String> predicate = s -> s.matches("\\d+");
String result = tranform(attributeMap, predicate);
谓词谓词=s->s.matches(\\d+);
字符串结果=tranform(attributeMap,谓词);

attributeMap.toString()
不执行此任务?不。@SzymonStepniak。我想检查条件的值并对进行更改。你可以看到输入输出。什么样的条件,什么样的变化?请在代码中解释,例如,如果值等于1111,则值不包含单引号,否则所有值都应包含在单引号内。@valamanoj到目前为止您尝试了什么?您编写的代码有什么问题?可以将键和值分离为字符串值,如c、c3、c4、FIRSTNAMe、'1111',ABCNAMe@valamanoj你在问这是否可能?一个或两个字符串?是的,我不知道我尝试过,但给我一个字符串的错误
String result = tranform(attributeMap, "1111"::equals);
System.out.println(result); // c=FIRSTNAMe,c3='1111',c4=ABCNAMe
Predicate<String> predicate = s -> s.matches("\\d+");
String result = tranform(attributeMap, predicate);