Cannot print inside forEach loop in stream java

594 Views Asked by At

The method "combination" should make combination of input arrays. And I like to get this stream of combination and save it into a file.

public void writeDot() {
    try (PrintStream out = new PrintStream(path, "UTF-8")) {
        out.print("digraph {\n");
        String[] arr = {"hyo", "ji", "yoo", "mi", "vi", "se", "ari"};
        combination(arr, 2, 0, new String[2])
                .stream()
                .map(a -> Arrays.toString(a).join(" -> "))
                .forEach(out::print);
        out.println(";\n");
        out.println("}");
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

Combination methods goes like this:

public List<String[]> combination(String[] arr, int len, int startPosition, String[] result) {
    if (len == 0) {
        //System.out.println(Arrays.toString(result));
        return null;
    }
    for (int i = startPosition; i <= arr.length - len; i++) {
        result[result.length - len] = arr[i];
        combination(arr, len - 1, i + 1, result);
        list.add(result);
    }
    return list;
}

Result I expected is:

digraph {
hyo -> ji;
ji -> hyo;

and so on..
}

But I only get:

digraph {
;

}

What's wrong with my code? please help me.

2

There are 2 best solutions below

0
talex On BEST ANSWER

String.join is a static method that accepts two parameters: delimiter and array of elements.

You pass no elements, so result is empty string.

Correct code is:

combination(arr, 2, 0, new String[2])
                .stream()
                .map(a->String.join(" -> ", a))
                .forEach(out::print);
3
corsiKa On

It appears you have some issues with your combination method which are not helping your case because you're recursively calling it with only ever making one new result array. Instead, try a better combination method - ideally use a well tested library for this, like apache commons or guava.

public static List<String[]> makePairsFromArray(String[] arr) {
    List<String[]> list = new ArrayList<>();

    for(int i = 0; i < arr.length - 1; i++) {
        for(int j = i + 1; j < arr.length; j++) {
             String[] pair = new String[2];
             pair[0] = arr[i]; 
             pair[1] = arr[j];
             list.add(pair);
             String[] opp = new String[2];
             opp[0] = arr[j];
             opp[1] = arr[i];
             list.add(opp);
        }
    }
    return list;
}

Additionally, you will need to update the map(join) method call as described by talex.