33

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.

ErikE
  • 48,881
  • 23
  • 151
  • 196
jason
  • 6,962
  • 36
  • 117
  • 198

3 Answers3

59

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.

Nick Holt
  • 33,455
  • 4
  • 52
  • 58
  • One question: Can I use this with Android? – jason Jul 13 '15 at 13:37
  • 1
    The Stream API was introduced with Java 8, which (at the time of writing) is yet to be supported (see http://stackoverflow.com/questions/23318109/is-it-possible-to-use-java-8-for-android-development) – Nick Holt Jul 14 '15 at 12:06
  • 1
    The default here is actually `null`—the default of all class types. Since C# allows primitives as generic type arguments (without boxing!!), the name `FirstOrDefault` hints that for value types, you'll get something besides `null` such as for `int`, `0`, and for a `struct`, an instance of that struct created using its default (parameterless) constructor. Unless it's a nullable value type, in which case you'll get `null` again, because that's actually equivalent to the class `Nullable`. – ErikE Sep 15 '17 at 00:22
4

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;
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Denis Lukenich
  • 3,084
  • 1
  • 20
  • 38
3

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

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71