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.
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.
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;
}
Even though there Java does not provide you with LINQ equal constructs but you can achieve some level what LINQ operations with Java 8 stream constructs.
such as one
List<String> items = new ArrayList<String>();
items.add("one");
items.add("two");
items.add("three");
Stream<String> stream = items.stream();
stream.filter( item -> item.startsWith("o") );
Take a look at java8 stream