我正在尝试使用 Java 8 ForEach 编写与以下内容等效的代码来对字符串数组进行编码。
public static void encode(String... stringsToEncode) {
for (int i = 0; i < stringsToEncode.length; i++) {
stringsToEncode[i] = URLEncoder.encode(stringsToEncode[i], "UTF-8");
}
}
// stringsToEncode = 10+111569+++8 as expected.
我已经实现了以下内容:
public static void encodeUsingForEach(String... stringsToEncode)
List<String> listOfStrings = Arrays.asList(stringsToEncode);
listOfStrings.forEach(s -> {
try {
s = URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
});
}
// listOfStrings = [10 11, 156, 9 8]
我缺少什么才能使encodeUsingForEach() 的输出与encode() 方法的输出等效?
最佳答案
您无法使用 forEach()
替换值,因为它仅使用对象而不返回它们。 lambda 内部的重新分配实际上没有任何作用,因为 arguments are passed by value in Java 。相反,尝试使用流来映射值并生成新列表:
List<String> listOfStrings = Arrays.stream(stringsToEncode)
.map(s -> {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
})
.collect(Collectors.toList());
关于java - 如何在 String 对象上使用 Java 8 forEach 对值进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45829440/