0
public class Main2 {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(2,4,3,-5,-7);

        Collections.sort(list);

        int i = 0;
        int j = list.size()-1;

        int min = 1000;

        while (true) {
             int sum = list.get(i)+list.get(j);

             if (mod(sum) < min) {
                 min = mod(sum);
             }
             if (sum < 0) {
                 i++;
             }
             else if (sum ==0 ) {
                 i++;
                 j--;
             }
             else {
                 j--;
             }

             if (j <= i) {
                 break;
             }
        }

        System.out.println(min);

    }
    private static int mod(int sum) {
        return sum < 0 ? -sum : sum;
    }
}

Above code is to find sum nearest to zero by adding any two element. But I am unable to figure out how (without using loop) stream is going to help in writing more cleaner, readable code. What i have seen if inside for loop if there is not much logic, then use of stream makes code cleaner.

2
  • 1
    Lets see if someone comes by to solve that problem using streams. But you know - who says that all problems can be "better" using streams? I find them helpful sometimes, but not all the times. The only real thing with streams: when you got a stream solution, you can try to go parallel just by changing to use parallelStream(). Try doing that with your solution ... Commented Dec 28, 2016 at 11:29
  • 1
    you are moving up and down the list with two indices (i and j) - I doubt you can find an elegant stream solution to do the same thing. Unless you change the algorithm. Also note that your mod method should probably be called abs - and you don't really need it: Math.abs(sum) should do the trick. Commented Dec 28, 2016 at 11:34

1 Answer 1

2

You could stream the list and flatMap it against the same list streamed again, and then use the stream's min method. The code would definitely be shorter, but whether or not it would be easier to read is in the eye of the beholder:

int min = list.stream()
              .flatMapToInt(i -> list.stream()
                                     .filter(j -> !i.equals(j))
                                     .mapToInt(j -> i + j)
                           )
              .map(Math::abs)
              .min()
              .getAsInt();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.