There are several methods that count the number of consonants in a word by a given parameter. Methods differ only in the type of argument they take:

public int countPhonotype(Consonant.Place place) { int count = 0; for(Consonant cons : this.transcription) { if (cons.getPlace().equals(place)) { count++; } } return count; } public int countPhonotype(Consonant.Manner manner) { int count = 0; for(Consonant cons : this.transcription) { if (cons.getManner().equals(manner)) { count++; } } return count; } 

I would like to take the common part into a separate method, but I cannot find a solution for how to pass the method there. I tried to understand the links to the methods, but the working version failed. I would be grateful for the help.

PS: there are actually more than two methods, so I would not like to “leave it as it is”.

  • Through an operator reference such as Class::method , through functional interfaces, through the Method class, through the Callable class Callable or through Lambda Expressions . - And

1 answer 1

Of course you can do

 private int countPhonotypeBy(Predicate<Consonant> p) { int count = 0; for(Consonant cons : this.transcription) { if (p.test(cons)) { count++; } } return count; } public int countPhonotype(Consonant.Place place) { return countPhonotypeBy(cons -> cons.getPlace().equals(place)); } public int countPhonotype(Consonant.Manner manner) { return countPhonotypeBy(cons -> cons.getManner().equals(manner)); } 

But you can go ahead and use to count the stream.

 private int countPhonotypeBy(Predicate<Consonant> p) { return (int) Arrays.stream(this.transcription).filter(p).count(); } 

That is, if the transcription is an array, the collections have their own stream method.

 private int countPhonotypeBy(Predicate<Consonant> p) { return (int) this.transcription.stream().filter(p).count(); } 
  • @ Alexey is a shorter syntax, which you wrote about in the commentary on the question - Stranger in the Q
  • @StrangerintheQ if we are talking about Class::method , then I do not see an opportunity to reduce something in this example in this way. Although it is possible that I miss the obvious. - extrn 11:03 pm