[英]Java equivalent of Where Clause in C# Linq
I can do this in C# : 我可以在C#中做到这一点:
int CheetahNumber = 77;
Animal Cheetah = Model.Animals
.Where(e => e.AnimalNo.Equals(CheetahNumber))
.FirstOrDefault();
For example in Java I have ArrayList<Animal> Animals
例如在Java中,我有
ArrayList<Animal> Animals
How can I query such an ArrayList? 我怎样才能查询这样的ArrayList? Thanks.
谢谢。
Java 8 introduces the Stream API that allows similar constructs to those in Linq. Java 8引入了Stream API ,它允许类似于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. 即使Java没有为您提供LINQ相等的构造,但是您可以在某种程度上实现使用Java 8流构造的LINQ操作。
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 看看java8流
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.