mercredi 1 juillet 2015

Java 8 Streams: Analyze same list elements

Code explains better:

Test Case

@org.junit.Test
public void test() {
    List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

    System.out.println(withoutStreams(values)); // Output: 1,9
    System.out.println(withStreamSol1Error(values)); // Compile time error
    System.out.println(withStreamSol2(values)); // Output: 1,9
}

Required Solution (Without Stream):

private List<Integer> withoutStreams(List<Integer> values) {
    // List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

    for (int index1 = 0; index1 < values.size(); index1++) {
        int value1 = values.get(index1);
        if (value1 == 10)
            return Arrays.asList(value1);
        for (int index2 = index1 + 1; index2 < values.size(); index2++) {
            int value2 = values.get(index2);

            if ((value1 + value2) == 10) {
                return Arrays.asList(value1, value2);
            }
        }
    }

    return Collections.emptyList();
}

My Attempt : With Stream: (Compile time error - mismatch)

private List<Integer> withStreamSol1Error(List<Integer> values) {
    List<Integer> exactEqual = values.stream().filter(value -> value.intValue() == 10).limit(1)
            .collect(Collectors.toList());

    // Compile Time Error
    if (exactEqual.isEmpty()) {
        IntStream.range(0, values.size() - 1)
                .forEachOrdered(index -> IntStream.range(index + 1, values.size() - 1)
                        .filter(index2 -> values.get(index) + values.get(index2) == 10).limit(1)
                        .collect(Collectors.toList()));
    }

    return Collections.emptyList();
}

With Stream (Working)

private List<Integer> withStreamSol2(List<Integer> values) {
    List<Integer> exactEqual = values.stream().filter(value -> value.intValue() == 10).limit(1)
            .collect(Collectors.toList());

    int index1 = 0;
    final List<Integer> result = new ArrayList<>();
    if (exactEqual.isEmpty()) {
        values.stream().forEach(value1 -> {
            if(!result.isEmpty()) // Query: How can stop outer forEach
                return;

            result.add(value1);
            result.addAll(values.stream().skip(index1).filter(value2 -> (value1 + value2) == 10).limit(1)
                    .collect(Collectors.toList()));
        });
    }

    return result;
}

Can anyone suggest a good solution for this problem?

Aucun commentaire:

Enregistrer un commentaire