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.
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.
There is nothing like LINQ for Java.
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.
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#.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With