Stream.toArray

Object[] toArray()
 A[] toArray(IntFunction generator)
 

简单地说这个方法就是把流转为数组。要把流转为集合可以使用collect方法,把流转为数组就用toArray方法。

无参方法返回的时候一个Object对象数组,有参数的方法返回数组数据类型根据该方法参数函数定义的数据类型来确定。Generator函数用来生成一个数组数据类型。

看例子:

void stream_toArray() {

        Object[] obarray = Stream.of("aa","bb","cc").toArray();

        int[] array = IntStream.of(12, 4, 4, 6, 10, 3, 6, 8, 9).toArray();

        long[] loarray = Stream.of("43","55","23","25","65").mapToLong(a -> Long.parseLong(a)).toArray();

    }

第一行代码,通过of方法直接生成一个流,然后直接toArray,返回的肯定是Object类型的数组,不论流中保存的是什么类型的元素都是返回Object类型数组。

第二行代码,这里使用IntStraem的of方法生成的是IntStream流,然后使用toArray方法返回的就是int类型的数组,LongStream和DoubleStream也可以生成确定数据类型的数组。

第三行代码,其实就是通过mapToLong方法把普通流转化为LongStream。

上面示例中第一行代码,如果不想返回Object对象数组,我就想指定数组类型为String怎么办?看下面代码:

String[] strArray = Stream.of("aa","bb","cc").toArray(String[]::new);

这个时候就用到了带参数的toArray方法了,这个方法的参数可以指定返回数组的数据类型。

再来2个例子:

Integer[] intArray = Stream.of(12, 4, 4, 6, 10, 3, 6, 8, 9).toArray(Integer[]::new);

User[] userArray = Stream.of(new User("111@qq.com","北京"),new User("222@qq.com","shanghai")).toArray(User[]::new);

最后这个例子很直接的诠释了带参数toArray方法的重要性,就是我可以把任何数据类型的流转为以其相同数据类型的数组。

优化代码,使用using块 参考 public bool SaveCheckPicture(string path, string fileName, Image img, int dpi = 600, int maxWidth = 0, int maxHeight = 0,out string msg ) { msg = string.Empty; try { // 计算缩放比例 float scale = (float)dpi / img.HorizontalResolution; // 计算缩放后的尺寸 int width = (int)(img.Width * scale); int height = (int)(img.Height * scale); // 如果指定了最大宽度或最大高度,则按比例缩放 //if (maxWidth > 0 && width > maxWidth) //{ // height = (int)(height * ((float)maxWidth / width)); // width = maxWidth; //} //if (maxHeight > 0 && height > maxHeight) //{ // width = (int)(width * ((float)maxHeight / height)); // height = maxHeight; //} // 创建缩放后的位图 Bitmap bmp = new Bitmap(width, height); // 设置位图的DPI bmp.SetResolution(dpi, dpi); // 创建绘图对象 Graphics g = Graphics.FromImage(bmp); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // 绘制缩放后的图片 g.DrawImage(img, new Rectangle(0, 0, width, height)); // 保存缩放后的图片 //bmp.Save(Path.Combine(path, fileName), System.Drawing.Imaging.ImageFormat.Jpeg); MemoryStream stream = new MemoryStream(); bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] data = stream.ToArray(); // 释放资源 stream.Dispose(); g.Dispose(); bmp.Dispose(); img.Dispose(); return SaveCheckPicture(path, fileName, data, out msg); // return true; } catch (Exception ex) { msg = ex.ToString(); return false; } }
05-27
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值