避免使用java streams-android

时间:2015-12-08 15:04:06

标签: java android stream

我有一个代码,但我想避免使用java流,因为android不支持流。这是我的代码:

import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;

public class VogelsApproximationMethod {

    final static int[] demand = {30, 20, 70, 30, 60};
    final static int[] supply = {50, 60, 50, 50};
    final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
    {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};

    final static int nRows = supply.length;
    final static int nCols = demand.length;

    static boolean[] rowDone = new boolean[nRows];
    static boolean[] colDone = new boolean[nCols];
    static int[][] result = new int[nRows][nCols];

    static ExecutorService es = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws Exception {
        int supplyLeft = stream(supply).sum();
        int totalCost = 0;

        while (supplyLeft > 0) {
            int[] cell = nextCell();
            int r = cell[0];
            int c = cell[1];

            int quantity = Math.min(demand[c], supply[r]);
            demand[c] -= quantity;
            if (demand[c] == 0)
                colDone[c] = true;

            supply[r] -= quantity;
            if (supply[r] == 0)
                rowDone[r] = true;

            result[r][c] = quantity;
            supplyLeft -= quantity;

            totalCost += quantity * costs[r][c];
        }

        stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
        System.out.println("Total cost: " + totalCost);

        es.shutdown();
    }

如果有人能帮助我,我将不胜感激,因为我无法理解流是如何工作的。

1 个答案:

答案 0 :(得分:0)

这很容易,你可以使用for循环作为 Mike M 在他的评论中建议见下面的例子:

int supplyLeft = 0;
int[] supply = {50, 60, 50, 50};
for (int i : supply) {
    supplyLeft += i;
}
System.out.println(supplyLeft); 

替换

int supplyLeft = stream(supply).sum();

如果你不想要foreach那么

int supplyLeft = 0;
for (int i = 0; i < supply.length; i++) {
    supplyLeft += supply[i];
}
System.out.println(sum); 

就迭代2D数组和替换java-8流而言如下所示

stream(result).forEach(a -> System.out.println(Arrays.toString(a)));

您可以根据自己的需要使用for loopArrays.deepToString(),例如:

//assume your array is below, you can replace it with results everywhere
int[][] costs= { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 },
                { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } };

for (int i = 0; i < costs.length; i++) {
    System.out.println(Arrays.toString(costs[i]));
}

以上for loop将按以下方式打印数组

[16, 16, 13, 22, 17]
[14, 14, 13, 19, 15]
[19, 19, 20, 23, 50]
[50, 12, 50, 15, 11]

如果您使用Arrays.deepToString(costs),则会得到如下所示的输出:

[[16, 16, 13, 22, 17], [14, 14, 13, 19, 15], [19, 19, 20, 23, 50], [50, 12, 50, 15, 11]]

以上替换