我已阅读 this相关帖子。谈到字符串操作,流似乎吸引了大量的仪式。如果你想将一个字符串解析为一个你可能想要对其进行一些操作的字符流,你需要将它们转换为 IntStream
首先,映射到Object
,然后转换 int
至 char
,最终类型转换了 char
至 String
然后返回它。
人们说命令式编程有仪式开销。如果我完全做错了,请纠正我。我的目的不是 mock ,而是更好地理解 Java 流,因为我通常很欣赏它们。
// Simple method which encrypts all chars in a string
String input = "Hel!lo";
String result = input.chars() // Need to convert into an IntStream
.mapToObj(e -> Character.toUpperCase((char) e)) // Need to map to Object (!) and then cast to char
.map(CryptoMath::encryptChar) // Calling the encryption
.map(String::valueOf) // Need to cast to String again...
.collect(joining("")); // Finally done
System.out.println(result);
最佳答案
如果您可以对 Unicode 代码点而不是字符进行操作,则它会比对 char
的操作简单一些。 :
String input = "Hel!lo";
String result = input.codePoints()
.map( Character::toUpperCase )
.collect( StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append )
.toString();
System.out.println(result);
不需要装箱,也不需要在收集点转换为字符串,并且您不太可能被输入数据中的代理对绊倒。实现满足更广泛输入集的东西不会那么痛苦的好时机之一。
关于string - Java 8 流是否只是不打算与字符和字符串一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809072/