如何将ArrayList <double>转换为2D数组?我想要一个矩阵

时间:2017-08-16 03:43:43

标签: java arrays matrix arraylist multidimensional-array

我有一个像这样的ArrayList:

50px

我从这段代码中得到了输出

[2.0, 3.0, 5.0, ...., 9.0] // has 30 value inside

那么,我可以将数组list = data [30]转换为2d array = data [6] [5] 吗? 也许喜欢这个输出

ArrayList<Double> data = new ArrayList<Double>();

        for (Document matrix : matrices) {

            Double column1 = matrix.getDouble("column1");
            data.add(column1);
            Double column2 = matrix.getDouble("column2");
            data.add(column2);
            Double column3 = matrix.getDouble("column3");
            data.add(column3);
            Double column4 = matrix.getDouble("column4");
            data.add(column4);
            Double column5 = matrix.getDouble("column5");
            data.add(column5);
        }

        System.out.println("Current array list is:"+data);

或者我必须制作6个不同的启动ArrayList来获取矩阵?

3 个答案:

答案 0 :(得分:1)

我刚才写了这篇关于矩阵的文章。它处理差异形式(列表,数组,2d数组等)。应该是你需要的

package com.bossanova.hitl.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author Dan
 *
 * @see This has moved to commons
 */
@Deprecated
public class ArrayUtils {

    private static Gson gson;
    static{
        gson = new Gson();
    }

    public static <T extends Number> T[][] convertListTo2DArray(List<T> elements, Class<T> numberClass, int rows, int cols) {
        if (rows * cols < elements.size()) {
            throw new IndexOutOfBoundsException("Theres not going to be enough room in the array for all the data");
        }
        @SuppressWarnings("unchecked")
        T[][] array = (T[][]) Array.newInstance(numberClass, rows, cols);
        int index = 0;
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                array[row][col] = elements.get(index);
                index++;
            }
        }
        return array;
    }

    public static double[][] convertDoubleListTo2DPrimativeArray(List<Double> elements, int rows, int cols) {
        Double[][] twoDArray = convertListTo2DArray(elements, Double.class, rows, cols);
        double[][] retVal = new double[rows][cols];
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                retVal[row][col] = twoDArray[row][col];
            }
        }
        return retVal;
    }

    public static List<Double> convert2DArrayToList(double[][] data) {
        int rows = data.length;
        int cols = data[0].length;
        List<Double> retVal = new ArrayList<>();
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                retVal.add(data[row][col]);
            }
        }
        return retVal;
    }

    public static double[][] deepCopy(double[][] original) {
        final double[][] result = new double[original.length][];
        for (int i = 0; i < original.length; i++) {
            result[i] = Arrays.copyOf(original[i], original[i].length);
        }
        return result;
    }

    public static double[][] convertJsonDoubleArrayTo2DArray(String json, int rows,int cols){
        return convertDoubleListTo2DPrimativeArray(convertJsonDoubleArrayToDoubleList(json), rows, cols);
    }

    public static List<Double> convertJsonDoubleArrayToDoubleList(String json){
        List<Double> doubleList = gson.fromJson(json, new TypeToken<List<Double>>(){}.getType());
        return doubleList;
    }
}

答案 1 :(得分:0)

只需做一些基本的算术来查找你想要的坐标。

static Double getXY(List<Double> list, int x, int y, int numberOfColumns) {
    return list.get(y * numberOfColumns + x);
}

答案 2 :(得分:0)

也许其他答案更好但这解决了我的问题:

import java.util.concurrent.TimeUnit

import org.openjdk.jmh.annotations._

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.util.Random
import scala.concurrent.ExecutionContext.Implicits.global

/**
  * Created by Yuval.Itzchakov on 21/08/2017.
  */
@State(Scope.Thread)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Array(Mode.AverageTime))
@Fork(5)
class MergeSortTest {

  var seq: Seq[Double] = _

  @Setup
  def setup(): Unit = {
    seq = (1 to 1000000).map(i => Random.nextDouble()).toVector
  }

  lazy val regressThreadhold = 10000

  def mergeSortedList[T](a: Seq[T], b: Seq[T])(implicit ord: Ordering[T]): Seq[T] = {
    def loop(a: Seq[T], b: Seq[T], acc: Seq[T]): Seq[T] = {
      if (a.isEmpty && b.isEmpty) acc
      else if (a.isEmpty) b.reverse ++: acc
      else if (b.isEmpty) a.reverse ++: acc
      else if (ord.lt(a.head, b.head)) loop(a.tail, b, a.head +: acc)
      else loop(a, b.tail, b.head +: acc)
    }

    loop(a, b, Seq()).reverse
  }

  def mergeSortAsync0[T](x: Seq[T])(implicit ord: Ordering[T]): Future[Seq[T]] =
    if (x.size <= regressThreadhold) Future(mergeSort(x)) else {
      val (left, right) = x.splitAt(x.size / 2)
      val Seq(leftSorted, rightSorted) = Seq(left, right).map(seq => Future(mergeSortAsync0(seq)).flatten)
      leftSorted.zip(rightSorted).map(pair => mergeSortedList(pair._1, pair._2))
    }

  def mergeSortAsync[T](x: Seq[T])(implicit ord: Ordering[T]): Seq[T] =
    Await.result(mergeSortAsync0(x), Duration.Inf)

  def mergeSort[T](x: Seq[T])(implicit ord: Ordering[T]): Seq[T] =
    if (x.size <= 1) x else {
      val (left, right) = x.splitAt(x.size / 2)
      val (leftSorted, rightSorted) = (mergeSort(left), mergeSort(right))
      mergeSortedList(leftSorted, rightSorted)
    }

  @Benchmark
  def benchMergeSortSync(): Unit = {
    mergeSort(seq)
  }

  @Benchmark
  def benchMergeSortAsync(): Unit = {
    mergeSortAsync(seq)
  }

  @Benchmark
  def benchScalaSort(): Unit = {
    seq.sorted
  }
}
相关问题