将system.out.print与java流一起使用

时间:2018-01-17 18:08:21

标签: java java-stream

我有以下代码将每个条目映射到print语句,但它显示错误。
我理解Stream().map()的方式有问题吗?

如何在流API中使用System.out.println()?我该如何更正以下代码?

public static void main(String[] args) {

    Properties p = new Properties();
    p.setProperty("name", "XYX");
    p.setProperty("email", "xyx@mail.com");
    p.setProperty("address", "addr-street-city");

    p.entrySet().stream().map(e ->
            System.out.println(" " + e.getKey().toString() + " " + e.getValue().toString() + ""));
}

3 个答案:

答案 0 :(得分:4)

p.entrySet().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));

p.forEach((key, value) -> System.out.println(key + " " + value));

答案 1 :(得分:1)

如果您想使用map

p.entrySet().stream()
            .map(e -> " "+e.getKey()+" "+e.getValue())
            .forEach(System.out::println);

答案 2 :(得分:0)

properties.entrySet().stream()
            .map(entry -> String.format("%s : %s", entry.getKey(), entry.getValue()))
            .forEach(System.out::println);
  • .map(...) - 将key-value转换为字符串格式
  • .forEach(...) - 打印字符串

您的输出应该如下:

address : addr-street-city
email : xyx@mail.com
name : XYX