Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream anyMatch failing with "Incompatible types" error

I want to print the contacts from my given set by number and I'm trying to do it with streams. With a little googling i saw people solving it the way I'm trying right now. But I'm getting this error Incompatible types: PhoneNumber is not convertible to CharSequence and i don't understand what i need to do. The error is in the method contactsByNumber Code: PhoneNumber.java

class PhoneNumber {

   private String name;
   private String number;

   public PhoneNumber(String name, String number) {
       this.name = name;
       this.number = number;
   }

   public String getName() {
       return name;
   }

   public String getNumber() {
       return number;
   }
}

PhoneBook

class PhoneBook {
    private Set<PhoneNumber> phoneNumbers;

    public PhoneBook() {
        this.phoneNumbers = new HashSet<>();
    }

    public void addContact(String name, String number) throws DuplicateNumberException {
        PhoneNumber pn = new PhoneNumber(name, number);
        if(phoneNumbers.contains(pn)) {
            throw new DuplicateNumberException(number);
         } else {
             phoneNumbers.add(new PhoneNumber(name, number));
         }
     }

     public void contactsByNumber(String number) {
          phoneNumbers.stream().parallel().anyMatch(number::contains);
     }
 }
like image 575
Stefan Avatar asked Dec 24 '22 01:12

Stefan


1 Answers

In this section:

public void contactsByNumber(String number) {
    phoneNumbers.stream().parallel().anyMatch(number::contains);
}

it is a Stream<PhoneNumber>, and you are trying to treat it as a String. You need to map it to it's name attribute:

public void contactsByNumber(String number) {
    phoneNumbers.stream().parallel().map(PhoneNumber::getName).anyMatch(number::contains);
}

However this method does nothing, as you ignore the result of anyMatch. If you wanted to print the results, you could change anyMatch to filter and then print:

public void contactsByNumber(String number) {
    phoneNumbers.stream()
                .parallel()
                .map(PhoneNumber::getName)
                .filter(number::contains)
                .forEach(System.out::println);
}

Also if you don't have a good reason to use a parallel Stream, I would recommend not using one, as it has a lot more overhead

like image 71
GBlodgett Avatar answered Dec 25 '22 14:12

GBlodgett