首先,设置一个流(Stream)-
Stream<Integer> stream = Stream.of(25, 30, 45, 50, 75, 100, 125, 150);
现在,声明一个Set并将此流转换为set-
Set<Integer> set = new HashSet<>(); stream.forEach(set::add); set.forEach(res -> System.out.println(res));
以下是在Java中将Stream转换为Set的程序-
import java.util.*; import java.util.stream.*; public class Demo { public static void main(String[] args) { Stream<Integer> stream = Stream.of(25, 30, 45, 50, 75, 100, 125, 150); Set<Integer> set = new HashSet<>(); stream.forEach(set::add); System.out.println("Stream to Set..."); set.forEach(res -> System.out.println(res)); } }
输出结果
Stream to Set... 50 100 150 25 75 45 125 30