Har*_*hra 1 java collections java-8 java-stream
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
SortedSet<Character> set= new TreeSet<Character>();
for (int i = 0; i < ALPHABET.length(); i++) {
set.add(new Character(ALPHABET.charAt(i)));
}
Run Code Online (Sandbox Code Playgroud)
我想用Java 8方式转换这个for循环.如果使用流可能会更好.输出将是包含Character的"set"对象.
String有一个方法,可以给你一个字符流.它实际上是一个IntStream我们只需要将它们转换为Characters然后转换collect为一组.
"foo".chars()
.mapToObj(chr -> (char) chr) // autoboxed to Character
.collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)
或使用TreeSet::new如其他已经显示,如果你需要一组进行排序.
IntStream.range(0, ALPHABET.length())
.mapToObj(ALPHABET::charAt)
.collect(Collectors.toCollection(TreeSet::new));
Run Code Online (Sandbox Code Playgroud)
我认为这是最简单的方法,保留了使用a的要求TreeSet.请注意,不需要使用索引迭代输入字符串,您可以直接迭代其字符.
SortedSet<Character> set =
ALPHABET.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toCollection(TreeSet::new));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
201 次 |
| 最近记录: |