这里有三种不同的解决方案来解决这个问题。每个解决方案首先过滤空字符串,否则可能会抛出 StringIndexOutOfBoundsException。
此解决方案与 Tagir 的解决方案相同,但添加了用于过滤空字符串的代码。我把它放在这里主要是为了与我提供的其他两种解决方案进行比较。
List<String> 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);
第二个解决方案使用Eclipse Collections,并利用了一个相对较新的容器类型CodePointAdapter,它是在7.0 版中添加的。
MutableList<String> 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);
第三个解决方案再次使用 Eclipse Collections,但使用 injectInto 和 StringBuilder 而不是 CodePointAdapter。
MutableList<String> 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);
注意:我是 Eclipse Collections 的提交者。