fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. static boolean containsOnlyNegatives(int[] integers) {
  11. // same as answer already given, but short-circuiting and bitwise
  12. return integers != null
  13. && !Arrays.stream(integers).anyMatch(i -> Integer.signum(-1 & i) != -1);
  14. }
  15.  
  16. static boolean containsPositive(int[] integers) {
  17. // no short-circuiting if the first element was tested positive
  18. return integers != null
  19. && Arrays.stream(integers).anyMatch(i -> Integer.signum(-1 & i) == 1);
  20. }
  21.  
  22.  
  23. public static void main (String[] args) throws java.lang.Exception
  24. {
  25. final int[] mixed = {-1, -2, 3, 0};
  26. final int[] negatives = {-1, -2};
  27. final int[] positives = {3, 4};
  28. var testCases = Map.of(
  29. "mixed", mixed
  30. , "only negatives", negatives
  31. , "only positives", positives
  32. );
  33.  
  34. testCases.forEach((k, v) ->
  35. System.out.println("Case: " + k
  36. + " | containsOnlyNegatives: " + containsOnlyNegatives(v)
  37. + " | containsPositive: " + containsPositive(v))
  38. );
  39. }
  40. }
Success #stdin #stdout 0.2s 38268KB
stdin
Standard input is empty
stdout
Case: only positives | containsOnlyNegatives: false | containsPositive: true
Case: only negatives | containsOnlyNegatives: true | containsPositive: false
Case: mixed | containsOnlyNegatives: false | containsPositive: true