Java 8 中可以使用 Stream API 和 reduce() 方法來對 List 中的字符串進行求和。
舉個例子,假設你有一個 List 叫做 "numbers",你可以這樣求和:
List<String> numbers = Arrays.asList("1", "2", "3", "4", "5");
String sum = numbers.stream().reduce("", (a, b) -> a + b);
或者這樣求和
List<String> numbers = Arrays.asList("1", "2", "3", "4", "5");
String sum = numbers.stream().collect(Collectors.joining());
這樣得到的結(jié)果就是 "12345"。
在這個例子中,我們使用 reduce() 方法對 List 中的所有字符串進行求和,其中第一個參數(shù)是初始值(即空字符串),第二個參數(shù)是一個 BiFunction,用來將當前和之前字符串相加。文章來源:http://www.zghlxwxcb.cn/news/detail-608414.html
第二種方法是使用 collect() 和 Collectors.joining() 方法將字符串連接起來.文章來源地址http://www.zghlxwxcb.cn/news/detail-608414.html
到了這里,關于java8 list對象string字符串求和的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!