我有一个Queue,我想将其转换为long[]并将其传递给计算百分位数的方法。

private final ConcurrentLinkedQueue<Long> holder = new ConcurrentLinkedQueue<>();


我正在使用ConcurrentLinkedQueue,因为我将多线程应用程序中的延迟(以毫秒为单位)插入上述的holder队列中,因此我想保持线程安全。

现在我的问题是如何将holder队列转换为long[]长数组,以便可以将其传递给下面的方法?有什么办法吗?

  public static long[] percentiles(long[] latencies, double... percentiles) {
    Arrays.sort(latencies, 0, latencies.length);
    long[] values = new long[percentiles.length];
    for (int i = 0; i < percentiles.length; i++) {
      int index = (int) (percentiles[i] * latencies.length);
      values[i] = latencies[index];
    }
    return values;
  }

最佳答案

看来ConcurrentLinkedQueue#toArray(T[] a)将为您提供90%的解决方案:

Long[] longs = holder.toArray(new Long[0]);


Long[]转换为long[]作为练习留给学生。 ;-)

10-05 20:49
查看更多