Java 相当于 C# Linq 中的 Where 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31381992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:00:21  来源:igfitidea点击:

Java equivalent of Where Clause in C# Linq

javalambda

提问by jason

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? Thanks.

如何查询这样的 ArrayList?谢谢。

采纳答案by Nick Holt

Java 8 introduces the Stream APIthat 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.

如果存在默认值,您显然需要进行锻炼,在这种情况下这看起来很奇怪,但我已经展示了它,因为这就是您问题中的代码所做的。

回答by kuhajeyan

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流

回答by Denis Lukenich

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;
}