Pencho Vlaskovski
Pencho Vlaskovski

Reputation: 61

Java Stream API comparing Strings in an array

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?

Upvotes: 2

Views: 1366

Answers (3)

Kamil Kozlowski
Kamil Kozlowski

Reputation: 66

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.

Upvotes: 3

Andy Turner
Andy Turner

Reputation: 140554

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.

Upvotes: 1

Eran
Eran

Reputation: 394156

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.

Upvotes: 6

Related Questions