javaconditional-operatoranagramintstream

incompatible types: bad type in conditional expression void cannot be converted to Boolean. please assist


Here is my code below.....

I am trying to use " (...)? IntStream.range(...).forEach(i->{......}):false;

public class CheckAnagram {

boolean status=false;
int countForStr1=0;
int countForStr2=0;
String str1ToLowerCase,str2ToLowerCase;
public boolean isAnagram(String str1, String str2){
   
    str1ToLowerCase=str1.toLowerCase().trim();
    str2ToLowerCase=str2.toLowerCase().trim();
    
    status = (str1ToLowerCase.length()==str2ToLowerCase.length())?
            IntStream.range(0, str1ToLowerCase.length()).forEach(i->{
                 char tempChar=str1ToLowerCase.charAt(i);
                 IntStream.range(0, str1ToLowerCase.length()).forEach(j->{
                     if(str1ToLowerCase.charAt(j)==tempChar)
                    countForStr1++;
                if(str2ToLowerCase.charAt(j)==tempChar)
                    countForStr2++;
                 });        
            }): false;
      }

}


Solution

  • In the statement

    status = (str1ToLowerCase.length()==str2ToLowerCase.length())?
    

    if the condition is true, there needs to be a value to be assigned to status ,however

    IntStream.range(0, str1ToLowerCase.length()).forEach(i->{
                     char tempChar=str1ToLowerCase.charAt(i);
                     IntStream.range(0, str1ToLowerCase.length()).forEach(j->{
                         if(str1ToLowerCase.charAt(j)==tempChar)
                        countForStr1++;
                    if(str2ToLowerCase.charAt(j)==tempChar)
                        countForStr2++;
                     });        
                })
    

    This block of code will not return anything, it just performing a few actions. There is nothing to be returned here. For each will not return anything , so you get void and the code is then assigning void to a variable. You can try something like this :

    status = str1ToLowerCase.length() == str2ToLowerCase.length();
            if (status) {            
                IntStream.range(0, str1ToLowerCase.length()).forEach(i -> {
                    char tempChar = str1ToLowerCase.charAt(i);
                    IntStream.range(0, str1ToLowerCase.length()).forEach(j -> {
                        if (str1ToLowerCase.charAt(j) == tempChar)
                            countForStr1++;
                        if (str2ToLowerCase.charAt(j) == tempChar)
                            countForStr2++;
                    });
                });
            }