Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Where Clause in C# Linq

Tags:

java

lambda

I can do this in C# :

int CheetahNumber = 77; Animal Cheetah = Model.Animals    .Where(e => e.AnimalNo.Equals(CheetahNumber))    .FirstOrDefault(); 

For example in Java I have ArrayList<Animal> Animals

How can I query such an ArrayList? Thanks.

like image 650
jason Avatar asked Jul 13 '15 11:07

jason


People also ask

What is where clause in Java?

The WHERE clause specifies a conditional expression that limits the values returned by the query. The query returns all corresponding values in the data store for which the conditional expression is TRUE. Although usually specified, the WHERE clause is optional.

Does Java have something like LINQ?

There is nothing like LINQ for Java.

What is LINQ in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.

Does Python have LINQ?

LINQ (Language Integrated Query) is a query language to deal with the query operators to perform the operations with the collections. In Python, we are able to achieve LINQ methods like C#.


2 Answers

Java 8 introduces the Stream API that allows similar constructs to those in Linq.

Your query for example, could be expressed:

int cheetahNumber = 77;  Animal cheetah = animals.stream()   .filter((animal) -> animal.getNumber() == cheetahNumber)   .findFirst()   .orElse(Animal.DEFAULT); 

You'll obviously need to workout if a default exists, which seems odd in this case, but I've shown it because that's what the code in your question does.

like image 124
Nick Holt Avatar answered Sep 24 '22 01:09

Nick Holt


You can try it by using streams:

public String getFirstDog(List<Animal> animals) {     Animal defaultDog = new Dog();     Animal animal = animalNames.stream(). //get a stream of all animals          filter((s) -> s.name.equals("Dog")).findFirst(). //Filter for dogs and find the first one         orElseGet(() -> defaultDog ); //If no dog available return an default animal.                                         //You can omit this line.     return animal; } 
like image 35
Denis Lukenich Avatar answered Sep 21 '22 01:09

Denis Lukenich