Lambda表达式实现java函数

时间:2015-01-16 19:57:56

标签: java lambda

该程序使用Java 6功能打印Pascal的三角形。 我想用Java 8中的Lambda实现更改printTriangle()函数中的逻辑。

public static void triangleusingAL() {
    int size = 7;

    List<Integer> triList = new ArrayList<Integer>();
    Map<Integer, List<Integer>> triMap = new LinkedHashMap<>();

    for (int i = 0; i < size; i++) {
        List<Integer> rowList = new ArrayList<Integer>();
        List<Integer> prevList = new ArrayList<Integer>();

        if (i == 0) {
            rowList.add(1); // add first element
            triMap.put(i, rowList);
            continue;
        }

        rowList.add(1);

        prevList = triMap.get(i - 1);
        for (int j = 1; j < i; j++) {
            int firstNo = prevList.get(j - 1);
            int secondNo = prevList.get(j);
            rowList.add(firstNo + secondNo);

        }

        rowList.add(1);

        triMap.put(i, rowList);
    }

public static void printTriangle(Map<Integer, List<Integer>> triMap) {
    System.out.println("\n Pascal Triangle using ArrayList");
    int pos = 5 * triMap.size();
    int startIndex = pos;

    Iterator entries = triMap.entrySet().iterator();
    while (entries.hasNext()) {
        List<Integer> rowList = new ArrayList<Integer>();
        Entry thisEntry = (Entry) entries.next();
        rowList = (List<Integer>) thisEntry.getValue();

        Iterator listItr = rowList.iterator();
        int j = 0;
        while (listItr.hasNext()) {
            if (j != 0) {
                pos = 10;
            }

            System.out.printf("%" + pos + "s", listItr.next());
            j = 1;
        }
        System.out.println();
        startIndex = startIndex - 5;
        pos = startIndex;
    }
}

任何数量的自定义更改对我都没问题。

1 个答案:

答案 0 :(得分:2)

这将有助于您入门

// value to keep track of the last row
long[][] values = [1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
[1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1]
[1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1]
... deleted ...
;
System.out.println("[1]");
IntStream.range(1, 66).mapToObj($ -> {
    // next row has one more number
    long[] next = new long[values[0].length + 1];
    // it starts and ends with a 1
    next[0] = next[next.length - 1] = 1;
    // calculate all the numbers in between
    IntStream.range(1, values[0].length)
            .forEach(i -> next[i] = values[0][i] + values[0][i - 1]);
    // save it for next time and turn it into a String
    return Arrays.toString(values[0] = next);
}).forEach(System.out::println);

打印

{{1}}
相关问题