流anyMatch失败,出现“不兼容类型”错误

时间:2019-02-05 17:41:56

标签: java java-stream

我想按编号从给定的集合中打印联系人,而我正在尝试使用流。稍作谷歌搜索,我看到人们以我现在正在尝试的方式解决它。但是我收到此错误Incompatible types: PhoneNumber is not convertible to CharSequence,但我不知道该怎么办。错误出在方法contactsByNumber中 码: 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;
   }
}

电话簿

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

1 个答案:

答案 0 :(得分:10)

在本节中:

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

它是Stream<PhoneNumber>,而您正在尝试将其视为String。您需要将其映射到它的name属性:

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

但是,此方法无济于事,因为您忽略了anyMatch的结果。如果要打印结果,可以将anyMatch更改为filter,然后打印:

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

此外,如果您没有充分的理由使用parallel流,我建议您不要使用it has a lot more overhead