Convert a for loop to concat String into a lambda expression

后端 未结 5 1694
予麋鹿
予麋鹿 2021-02-03 22:37

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

5条回答
  •  别跟我提以往
    2021-02-03 22:59

    Here are three different solutions to this problem. Each solution filters empty strings first as otherwise StringIndexOutOfBoundsException may be thrown.

    This solution is the same as the solution from Tagir with the added code for filtering empty strings. I included it here primarily to compare to the other two solutions I have provided.

    List list =
        Arrays.asList("the", "", "quick", "", "brown", "", "fox");
    StringBuilder builder = list.stream()
        .filter(s -> !s.isEmpty())
        .mapToInt(s -> s.codePointAt(0))
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append);
    String result = builder.toString();
    Assert.assertEquals("tqbf", result);
    

    The second solution uses Eclipse Collections, and leverages a relatively new container type called CodePointAdapter that was added in version 7.0.

    MutableList list =
        Lists.mutable.with("the", "", "quick", "", "brown", "", "fox");
    LazyIntIterable iterable = list.asLazy()
        .reject(String::isEmpty)
        .collectInt(s -> s.codePointAt(0));
    String result = CodePointAdapter.from(iterable).toString();
    Assert.assertEquals("tqbf", result);
    

    The third solution uses Eclipse Collections again, but with injectInto and StringBuilder instead of CodePointAdapter.

    MutableList list =
        Lists.mutable.with("the", "", "quick", "", "brown", "", "fox");
    StringBuilder builder = list.asLazy()
        .reject(String::isEmpty)
        .collectInt(s -> s.codePointAt(0))
        .injectInto(new StringBuilder(), StringBuilder::appendCodePoint);
    String result = builder.toString();
    Assert.assertEquals("tqbf", result);
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题