Is there a more efficient way to compare 3+ elements in an If statement?

I am writing a program to assign a class, and I want to compare several elements in an array for equivalence. My statement basically looks like this:

if (a == b && b == c && c == d && d == e && e == f) {
   // do stuff
}

This condition seems incredibly detailed, and I wonder if there is a shorter way to write it.

+4
source share
3 answers

It may seem verbose, but at least it is quite effective and understandable.

Do not overdo the optimizing code for short.

You can easily create a helper function

boolean allEqual(Object ... objs) {
    for(int i = 1; i < obj.length; i++) {
      if (!objs[i].equals(objs[0])) {
        return false;
      }
    }
    return true;
}

But this will create additional objects; in particular with primitive values:

if (allEqual(1.1,2.1,3.1,4.1))

5 , .

, ==, equals.

+3

, , , , :

public static < E > boolean areAllEqual( E[] inputArray ){
    Set<E> mySet = new HashSet<E>(Arrays.asList(inputArray));
    return mySet.size() == 1;
}    

:

import java.util.*;
public class HelloWorld{
    public static < E > boolean areAllEqual( E[] inputArray ){
        Set<E> mySet = new HashSet<E>(Arrays.asList(inputArray));
        return mySet.size() == 1;
    }    
     public static void main(String []args){
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'H', 'H', 'H', 'H' };

        System.out.println("It should work");
        if (areAllEqual(intArray))
            System.out.println("inarray Yes");
        else
            System.out.println("inarray No");

        if (areAllEqual(doubleArray))
            System.out.println("doubleArray Yes");
        else
            System.out.println("doubleArray No");

        if(areAllEqual(charArray))
            System.out.println("charArray  Yes");
        else
            System.out.println("charArray  No");                            
     }
}

:

It should work
inarray No
doubleArray No
charArray  Yes  // all elements in char array are eq
+2

Java 8 , , :

int[] numbers = {1, 2, 3, 4, 5};
if (Arrays.stream(numbers).allMatch(i -> (i == numbers[0]))) {
    //they are equal
}

:

  • IntStream ( , IntStream)
  • , true IntPredicate.
  • IntPredicate - i -> (i == numbers[0]), i (i == numbers[0]).

, , , :

public static boolean allEquals(final int[] input) {
    return (input.length > 0 && Arrays.stream(input).allMatch(i -> i == input[0]));
}

, true false, ... ?

, , . , :

public static <T> boolean allEquals(final T[] input) {
    return (input.length > 0 && Arrays.stream(input).allMatch(i -> i.equals(input[0])));
}

, , , , , varargs, , :

public static <T> boolean allEquals(final T... input) {
    return (input.length > 0 && Arrays.stream(input).allMatch(i -> i.equals(input[0])));
}

, , , .

+1

Source: https://habr.com/ru/post/1530040/


All Articles