将 Map 转换为 Java 中 Stream 的程序
首先,创建一个 Map 并设定值 −
Map<Integer, String> map = new HashMap<>(); map.put(1, "Kevin"); map.put(2, "Ryan"); map.put(3, "Nathan"); map.put(4, "Ricky"); map.put(5, "Shane"); map.put(6, "Adam");
现在,将 Map 转换为 Stream −
Stream<Map.Entry<Integer, String> > stream = map.entrySet().stream(); System.out.println("Stream (Map to Stream) = "+ Arrays.toString(stream.toArray()));
示例
以下是在 Java 中将 Map 转换为 Stream 的程序 −
import java.util.*; import java.util.stream.*; public class Demo { public static void main(String args[]) { Map<Integer, String> map = new HashMap<>(); map.put(1, "Kevin"); map.put(2, "Ryan"); map.put(3, "Nathan"); map.put(4, "Ricky"); map.put(5, "Shane"); map.put(6, "Adam"); System.out.println("Map = " + map); Stream<Map.Entry<Integer, String> > stream = map.entrySet().stream(); System.out.println("Stream (Map to Stream) = "+ Arrays.toString(stream.toArray())); } }
输出
Map = {1=Kevin, 2=Ryan, 3=Nathan, 4=Ricky, 5=Shane, 6=Adam} Stream (Map to Stream) = [1=Kevin, 2=Ryan, 3=Nathan, 4=Ricky, 5=Shane, 6=Adam]
广告