【问题标题】:Apply changes to Map values using Java 8 Streams使用 Java 8 Streams 对 Map 值应用更改
【发布时间】:2018-03-24 02:05:13
【问题描述】:

我想使用 java 8 更改地图值。

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

更改后,字符串的输出应如下所示

c='FIRSTNAMe',c3=111,c4='ABCNAMe' 

谁能帮帮我。

【问题讨论】:

  • attributeMap.toString() 不工作?
  • 没有 .@SzymonStepniak 。我想检查条件的值并更改为 .你可以看到输出。
  • 什么样的条件,有什么变化?请在代码中说明
  • 例如,如果 value 等于 1111,则 value 不包含单引号,否则所有 value 都应该包含在单引号内。
  • @valamanoj 到目前为止您尝试过什么?你写的代码有什么问题?

标签: collections filter java-8 java-stream


【解决方案1】:

您可以创建一个方法 transform 并传递一个 Predicate 以了解何时引用或不引用:

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(",")));
}

然后这样称呼它:

String result = tranform(attributeMap, "1111"::equals);
System.out.println(result); // c=FIRSTNAMe,c3='1111',c4=ABCNAMe

如果您只想引用数字,只需使用不同的Predicate:

Predicate<String> predicate = s -> s.matches("\\d+");
String result = tranform(attributeMap, predicate);

【讨论】:

  • 可以将键和值分离成字符串值,如 c,c3,c4,FIRSTNAMe,'1111',ABCNAMe
  • @valamanoj 你在问这是否可能?一个或两个字符串?
  • 是的,我不知道我已经尝试过,但是给我一个字符串的错误
猜你喜欢
  • 2015-06-19
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
相关资源
最近更新 更多