将for循环转换为concat String为lambda表达式 [英] Convert a for loop to concat String into a lambda expression

查看:899
本文介绍了将for循环转换为concat String为lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下for循环遍历字符串列表,并将每个单词的第一个字符存储在 StringBuilder 中。我想知道如何将其转换为lambda表达式

I have the following for loop which iterates through a list of strings and stores the first character of each word in a StringBuilder. I would like to know how can I transform this to a lambda expression

StringBuilder chars = new StringBuilder();
for (String l : list) {
    chars.append(l.charAt(0));
}  


推荐答案

假设你调用<$ c之后,我想你只是在寻找 toString()上的 StringBuilder oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#joining - > Collectors.joining() ,在将每个字符串映射到单字符子串后:

Assuming you call toString() on the StringBuilder afterwards, I think you're just looking for Collectors.joining(), after mapping each string to a single-character substring:

String result = list
    .stream()
    .map(s -> s.substring(0, 1))
    .collect(Collectors.joining());

示例代码:

import java.util.*;
import java.util.stream.*;

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("foo");
        list.add("bar");
        list.add("baz");
        String result = list
            .stream()
            .map(s -> s.substring(0, 1))
            .collect(Collectors.joining());
        System.out.println(result); // fbb
    }
}

注意使用 substring 而不是 charAt ,因此我们仍然有一串字符串。

Note the use of substring instead of charAt, so we still have a stream of strings to work with.

这篇关于将for循环转换为concat String为lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆