0

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;
      }

}

  • 2
    The code basically is `(someCondition) ? IntStream.range(...).forEach(i->{...}) : false` and `forEach` does not return anything / returns `void`. – luk2302 Jun 29 '21 at 12:11
  • Oh so I have to return something in the forEach method? – Tsebo Mokoena Jun 29 '21 at 12:30
  • You cannot return anything from that method, it is a stream terminating method and cannot be changed. Instead you should remove the entire ternary inline if and instead write a far more readable and expressive `if (someCondition) { IntStream stuff; status = true; } else { status = false; }` – luk2302 Jun 29 '21 at 12:32

1 Answers1

0

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++;
                });
            });
        }
MSS
  • 16
  • 3