-2

I created the following lambda to represent a BiPredicate.

(s1, s2) -> s1.getArtist().contains(s2.getArtist()) || s2.getArtist().contains(s1.getArtist())

Now I'm wondering if there is a way to make this more concise, maybe by using a method invocation or something else. I would prefer not to create extra variables and keep it a one-liner, but I am still open for other solutions if they make sense.

xeruf
  • 2,602
  • 1
  • 25
  • 48
  • 1
    I don't see any need for improvement here. – achAmháin Oct 27 '17 at 15:43
  • 2
    What's the problem with this so that you want to improve it? Of course you could provide/use a method that checks if either string contains the other and call it but besides that? Hint for writing a method: you could first check which of those strings is the longer and then just check `longer.contains(shorter)` as it can't be the other way round - and if both are of equal length then just choose one to be "longer". Note that this would probably not make much of a difference unless you have _really_ long artist names. – Thomas Oct 27 '17 at 15:44

1 Answers1

0

Some example of a 'faster' one - I picked special Strings to test, because java contains method already checks the length, which makes this approach and your approach basically the same if Strings differ in length (one contains is cut basically immediately after checking that first argument has shorter length). Also, since contains shortcuts after it finds that it cannot be true anymore, I made them differ only at the end. They are both really long Strings, you won't possibly encounter such Strings in your real world.

This approach is 2 times faster, because your is making a full check twice and this only once, but the difference is negligible, in a real benchmark it would be even smaller. And the Strings are cherry picked for the difference to be the biggest possible, so...

In conclusion: it's fine as it is if you want, but actually to me this version looks cleaner.

public static void main(String[] args) {
  String a = "";
  String b = "";

  Random random = new Random();
  StringBuilder builder = new StringBuilder(119999999);

  for(long i = 0; i < 119999999; i++)
    builder.append((char) random.nextInt());

  a = builder.toString() + "zzzzzzzzz";
  b = a.substring(0, a.length() - 9) + "dsadsasda";

  Instant start = Instant.now();

  boolean test = a.length() > b.length() ? a.contains(b) : b.contains(a);
  //boolean test = a.contains(b) || b.contains(a);

  if(test)
    System.out.println("OK");

  System.out.println(Duration.between(start, Instant.now()).toMillis());
}
Shadov
  • 5,421
  • 2
  • 19
  • 38