Ay0m3 Ay0m3 - 1 month ago 10
Java Question

Does the .NET predicate exists in Java?

Im new to Java, and I'm working on list at the moment. I have a list of "word", each word has a specific id (int). In .NET, I used to find a "word" by its id by (where data is my list, and w the word im looking for):

int index = data.FindIndex(s => s.id == w.id);


It's returning me an index then i can access the word by data[index]. I would like to know if something similar exists in Java, such as data.Any(), data.OrderBy(). Thanks in advance.

Answer

Java 8 Solution

I've never worked with .NET, but I do with java, so I can image what you're trying to do here.

Let's supose that your data implements List<T> interface as you said. You can use a filter function with nice lambdas, look:

int index = data.stream()
        .filter(word -> word.id == w.id)
        .map(word -> word.id)
        .findAny()
        .get();

Stream & Filter explained

The .stream() method will give you the stream that we need in order to filter and apply other fancy functions.

Then you .filter() the elements in the stream using a lambda expression that matches your requeriments (For what I've seen above, you're familiar with this).

The .findAny() returns you an 'optional' integer (Can be here or not) and you retrieve it's value with the .get() method.

Additionaly you can replace the .get() with a .orElse(-1) to get a -1 if the integer was not found.


Java 7 and prior

Unfortunately streams and lambdas are a java 8 thing, so to archieve this you should implement a less elegant solution, like this:

Word found = null;
for (Word s : words){
    if (s.id == w.id){
        found = s;
    }
}
//Check if was null or not here.
Comments