是否可以使用IntStream向数组添加添加元素?

时间:2019-10-03 14:55:56

标签: java lambda java-stream

我在cpp中使用了这个宏

forn(i,3) cin>>arr[n]; //assume arr initialised earlier
  

因此,我尝试使用lambda和IntStream在Java中实现此目标

  Scanner sc = new Scanner(System.in);
  IntStream.range(0, 5).map(i->arr[i]).forEach(e->e=sc.nextInt());

但是我知道流不能操纵底层的数据结构。所以我可以使用流来实现这一点,还是必须创建自己的功能接口来实现?谢谢

2 个答案:

答案 0 :(得分:3)

只需将代码更改为

Scanner sc = new Scanner(System.in);
IntStream.range(0, 5).forEach(i -> arr[i] = sc.nextInt());

但也请注意,这对于Streams来说不是一个很好的用例。一个简单的循环可能更合适。

答案 1 :(得分:2)

在映射作为输入提供的整数时,您似乎正在寻找using System; using System.IO; using System.IO.Pipes; class PipeClient { static void Main(string[] args) { using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "DMXServer", PipeDirection.In)) { // Connect to the pipe or wait until the pipe is available. Console.Write("Attempting to connect to pipe..."); pipeClient.Connect(); Console.WriteLine("Connected to pipe."); Console.WriteLine("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances); using (StreamReader sr = new StreamReader(pipeClient)) { // Display the read text to the console string temp; while ((temp = sr.ReadLine()) != null) { Console.WriteLine("Received from server: {0}", temp); } } } Console.Write("Press Enter to continue..."); Console.ReadLine(); } } toArray一起使用:

IntStream