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.
modmethod should probably be calledabs- and you don't really need it:Math.abs(sum)should do the trick.