2

I will be happy if someone can explain why I can not compare String in an array using the Stream API in Java.

I am trying to filter only the pairs when the first word is before the second lexicographically.

String[] input = { "Apple", "Banana" };

    Arrays.stream(input)
            .filter( (a,b)-> a.compareTo(b)< 0 )

It seems that Java doesn't understand, that "b" is a String, but why?

1
  • Because streams do not do magic. Commented Oct 16, 2017 at 12:14

3 Answers 3

6

filter expects a Predicate<T> (or to be more exact, Predicate<? super T>), where T is the type of the Stream element (String in your case).

(a,b)-> a.compareTo(b)< 0 cannot be interpreted as a Predicate<T>, since the Predicate's boolean test(T t) method takes just one argument, not two.

filter is applied on each element of a Stream separately. There are no pairs in your Stream.

Sign up to request clarification or add additional context in comments.

Comments

3

If you have more pairs to compare, this could be a help:

public class Main {

    public static void main(String[] args) {

        String[][] input = {{ "Apple", "Banana" }, 
                            {"Orange", "Apple"}, 
                            {"Banana", "Orange"}};

        Arrays.stream(input)
                   .filter(x -> x[0].compareTo(x[1]) < 0)
                   .forEach(x -> System.out.println(Arrays.toString(x)));

    }

}

And now the output should look like:

[Apple, Banana]
[Banana, Orange]

Hope it helps you with your problem.

2 Comments

On second thought this might be exactly what he wants.
yeah it might be misunderstanding... But he wrote about filtering out "pairs", so I thought these pairs are filtered out from something bigger and he only can't handle with the condition inside one pair. Anyway, it's my very first answer and what you wrote before is a precious tip, thanks ;)
1

If you want to compare pairs, you need to "make" the pairs yourself somehow, e.g.

IntStream indexes =
    IntStream.range(0, input.length-1)
                // Via i you implicitly have access to the pair
                // (input[i], input[i+1])
        .filter(i -> input[i].compareTo(input[i+1]) < 0);

This yields the indexes of elements lexicographically before their following element.

You can do further operations on this stream; but it's not entirely clear what result you expect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.