如何在 Java 中将 Stream 转换成 TreeSet?
首先,我们创建一个 Stream
Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland");
现在,将 Stream 转换成 TreeSet
Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));
以下是一个在 Java 中将字符串转换成 TreeSet 的示例
示例
import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland"); Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new)); set.forEach(val -> System.out.println(val)); } }
输出
Armenia Australia Canada India Poland UK US
广告