I am using String.equals() sentence in If conditional statement, is there any method or method to reduce it further?

Asked 2 years ago, Updated 2 years ago, 134 views

Currently, I am writing an if sentence as below. By the way, I want to compare the word "WORDS" with the corresponding objects and the equivalents of a specific word, is there a way to make it simpler? Of course, the object is of the String type.Of course, there is a way to compare "WORDS" with the entire list by putting it in the ArrayList, but I'm asking if there are any other specific methods.

if("WORDS".equals(object1) || "WORDS".equals(object2) || "WORDS".equals(object3) || "WORDS".equals(object4) || "WORDS".equals(object5) || "WORDS".equals(object6) || "WORDS".equals(object7) || "WORDS".equals(object8)  || "WORDS".equals(object9) || "WORDS".equals(object10)) {
    THEN do Something
}

java if문 equals

2022-09-22 21:43

2 Answers

If you use JAVA 8, you can do it simply in a lambda style as follows.

import java.util.List;
import java.util.Arrays;

class CodeRunner{
    public static void main(String[] args){
        List<String> myList = Arrays.asList("WORD", "ANOHTER", "WORDS");
        boolean results = myList.stream().anyMatch(str -> str.equals("WORDS"));

        System.out.println("Results = " + results);
    }
}

If not, it would be better to use anyMatch function similar to the following.

// If the word is null, this is not covered here.
boolean anyMatch(String word, String... objects) {
    boolean match = false;
    for( String object: objects ) {
        match = match || word.equals(object);        
    }
    return match;
} 

Or...

boolean anyMatch(String word, String... objects) {
    boolean match = false;
    for( int i=0; !match && i<objects.length; i++) {
        match = match || word.equals(objects[i]);        
    }
    return match;
} 


2022-09-22 21:43

If you create a function like the following, you can implement the function you want.

As far as I know, there is no method provided by Java.

/**
 * * @param word
 * * @param caseSensitive
 * * @param datas
 * * @return
 */
public static boolean equals(String word, boolean caseSensitive, String... datas) {
    for (String s : datas) {
        if (!caseSensitive) {
            if (s.equals(word)) {
                return true;
            }
        } } else {
            if (s.equalsIgnoreCase(word)) {
                return true;
            }
        }
    }
    return false;
}

Use:

if("WORDS", false, obj1, obj2, obj3){ // obj1~obj3 can be divided into arrays or commas
        //TODO
}


2022-09-22 21:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.