簡體   English   中英

Java 如何將兩個 arrays 與減少 function 合並為一個,如果可能的話?

[英]Java how to reduce/combine two arrays into one with the reduce function, if possible?

我有這個代碼:

String[] arr1 = {"asd1", "asd2", "asd3", "asd4", "asd5", "asd6", "asd7"};
    String[] arr2 = {"asd8", "asd9", "asd10", "asd11", "asd12", "asd13", "asd14"};

    String[] concatenated = Stream.of(arr1, arr2)
           .flatMap(Stream::of)
           .toArray(String[]::new);

    String[] concatenated = Stream
            .concat(Arrays.stream(arr1), Arrays.stream(arr2))
            .toArray(String[]::new);

    String[] concatenated = Stream.of(arr1, arr2)
            .reduce(new String[arr1.length + arr2.length],
                    (String[] a, String[] b) -> )); ///// how to proceed from here?

    System.out.println(Arrays.toString(concatenated));

我在玩,我沒有設法找到如何使用減少 function 將它們結合起來得到這個結果:

[asd1, asd2, asd3, asd4, asd5, asd6, asd7, asd8, asd9, asd10, asd11, asd12, asd13, asd14]

注意:順序並不重要,重要的是通過減少 function 將它們放入一個數組中。

可以用reduce做到嗎?

好吧,目前這是我想出的最好的,如果有人感興趣的話:

String[] concatenated = Stream
            .of(arr1, arr2)
            .reduce((a, b) -> {
                String[] result = Arrays.copyOf(a, a.length + b.length);
                System.arraycopy(b, 0, result, a.length, b.length);
                return result;
            })
            .orElseThrow();

    Stream.of(arr1, arr2)
            .reduce((a, b) -> {
                String[] result = Arrays.copyOf(a, a.length + b.length);
                System.arraycopy(b, 0, result, a.length, b.length);
                return result;
            })
            .ifPresent(strings -> System.out.println(Arrays.toString(strings)));

    Optional<String[]> concatenated2 = Stream
            .of(arr1, arr2)
            .reduce((a, b) -> {
                String[] result = Arrays.copyOf(a, a.length + b.length);
                System.arraycopy(b, 0, result, a.length, b.length);
                return result;
            });

    System.out.println(Arrays.toString(concatenated));

    concatenated2.ifPresent(strings -> System.out.println(Arrays.toString(strings)));

不完全是我要找的。 我很高興看到是否有人可以使用 reduce 提出更清潔的解決方案來解決這個問題。 我知道如果我將 reduce 的主體放在方法引用或其他東西中,我可以讓它更干凈,但事實並非如此。

這行得通。 這是人為的。 但是,恕我直言,任何使用reduce的方法都是人為的,因為有更好的方法。

String[] result = Stream.of(arr1, arr2)
                .flatMap(Arrays::stream)
                .reduce("", (s1, s2) -> s1 + s2 + ",").split(",");

System.out.println(Arrays.toString(result));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM