如何使用Java 8 Stream映射和收集原始返回类型 [英] How to map and collect primitive return type using Java 8 Stream

查看:131
本文介绍了如何使用Java 8 Stream映射和收集原始返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java 8流中的新手,我想知道是否有方法可以对返回byte并接受int作为参数的方法执行forEach/map调用.

I am new in Java 8 streams and I am wondering if there is way to perform forEach/map call on method returning a byte and accepting an int as parameter.

示例:

public class Test {
   private byte[] byteArray; // example of byte array

   public byte getByte(int index) {
      return this.byteArray[index];
   }

   public byte[] getBytes(int... indexes) {
      return Stream.of(indexes)
             .map(this::getByte) // should return byte
             .collect(byte[]::new); // should return byte[]
   }
}

您可能会猜到,getBytes方法不起作用. "int[] cannot be converted to int" foreach可能缺少某个地方,但个人无法弄清楚.

As you may guess, the getBytes method not working. "int[] cannot be converted to int"Probably somewhere is missing foreach, but personally cant figure it out.

但是,这是一种行之有效的老式方法,我想将其重写为Stream.

However, this is working, old-fashioned approach which I would like to rewrite as Stream.

byte[] byteArray = new byte[indexes.length];
for ( int i = 0; i < byteArray.length; i++ ) {
   byteArray[i] = this.getByte( indexes[i] );
}
return byteArray;

推荐答案

您可以编写自己的Collector并使用ByteArrayOutputStream构建byte[]:

You can write your own Collector and build your byte[] with an ByteArrayOutputStream:

final class MyCollectors {

  private MyCollectors() {}

  public static Collector<Byte, ?, byte[]> toByteArray() {
    return Collector.of(ByteArrayOutputStream::new, ByteArrayOutputStream::write, (baos1, baos2) -> {
      try {
        baos2.writeTo(baos1);
        return baos1;
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    }, ByteArrayOutputStream::toByteArray);
  }
}

并使用它:

public byte[] getBytes(int... indexes) {
  return IntStream.of(indexes).mapToObj(this::getByte).collect(MyCollectors.toByteArray());
}

这篇关于如何使用Java 8 Stream映射和收集原始返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆