I've implemented the same function with different approaches, can anybody tell me why my last function doesn't print false?

Cristian Mateica :
public static void main(String[] args) {         
  System.out.println(hasPairWithSum(new int[] { 12, 4, 3, 4, 1, 7 }, 9));        
  System.out.println(hasPairWithSum2(new int[] { 12, 4, 3, 4, 1, 7 }, 9));       
  System.out.println(hasPairWithSum3(new int[] { 12, 4, 3, 4, 1, 7 }, 9));  
}

public static boolean hasPairWithSum(int[] intArray, int sum) {         
  int len = intArray.length;        
  for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
                if (intArray[i] + intArray[j] == sum) {
                    return true;
                }
        }
  }         
  return false;
}

public static boolean hasPairWithSum2(int[] intArray, int sum) {         
    HashSet<Integer> mySet = new HashSet<Integer>();
    int len = intArray.length;
    for (int i = 0; i < len; i++) {
        if (mySet.contains(intArray[i])) {
                return true;
        }
        mySet.add(sum - intArray[i]);
    }
    return false;
}

public static boolean hasPairWithSum3(int[] intArray, int sum) {         
    HashSet<Integer> mySet = new HashSet<Integer>();
    int len = intArray.length;
    return IntStream.range(0, len).mapToObj(i -> {
        if (mySet.contains(intArray[i])) {
                return true;
        }
        mySet.add(sum - intArray[i]);
        return false;
    }) != null;
}
Maxim Popov :

Streams are lazy in Java. You need to call a terminal operation for starting evaluating the stream

"< U > Stream< U > mapToObj(IntFunction< ? extends U > mapper)" is not a terminal operation and it always returns Stream< Boolean > object, and it always not null.

You can modify your code like this, but I'm not sure that it's a good practice for using streams:

public static boolean hasPairWithSum3(int[] intArray, int sum) {         
    HashSet<Integer> mySet = new HashSet<Integer>();
    int len = intArray.length;
    return IntStream.range(0, len).anyMatch(i -> {
        if (mySet.contains(intArray[i])) {
                return true;
        }
        mySet.add(sum - intArray[i]);
        return false;
    });
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8103&siteId=1