假设以下是我们的Set-
Set<Integer> set = new HashSet<>(Arrays.asList(15, 40, 60, 90, 120, 150, 200));
现在,创建一种将上述设置转换为流的方法。
Stream<Integer>streamOfInteger = convertSet(set);
方法-
private static <T> Stream<T> convertSet(Set<T> set) { return set.stream(); }
以下是使用泛型将Java中的Set转换为Stream的程序-
import java.util.*; import java.util.stream.*; import java.util.function.*; public class Demo { private static <T> Stream<T> convertSet(Set<T> set) { return set.stream(); } public static void main(String args[]) { Set<Integer> set = new HashSet<>(Arrays.asList(15, 40, 60, 90, 120, 150, 200)); System.out.println("Set = " + set); Stream<Integer>streamOfInteger = convertSet(set); System.out.println("Stream (Set to Stream) = "+ Arrays.toString(streamOfInteger.toArray())); } }
输出结果
Set = [150, 40, 120, 200, 90, 60, 15] Stream (Set to Stream) = [150, 40, 120, 200, 90, 60, 15