Andi Keikha
Andi Keikha

Reputation: 1316

How to query a list of a class in java

I have class named class1 with two members, member1 and member2. I want to query on an ArrayList of class1 based on member1. We could do this in C# very easy using linq. and I found out that in java we can use libraries like what that has proposed in:

Is there a Java equivalent for LINQ?

However I don't have the time to learn this library, it has a loooot of jar files in its library and I don't know which one I should import to use the functionality I need. It seems it takes time. Can someone give me a programming hint, an equivalent program that can be replaced with that query. It seems I cannot think out of the box of linq. Is there any way to do that query without using these kinds of libraries?

Upvotes: 0

Views: 271

Answers (1)

Ghostkeeper
Ghostkeeper

Reputation: 3050

LINQ can do a lot of things and there is no single alternative for it. Java has no LINQ library, it's a .NET thing. You can do a lot of common LINQ operations in Java 8 though with streams and functional programming, such as your example:

Class1[] arr = ...
List<Class1> filteredList = stream(arr).filter(e -> e.member1 == val).collect(toList());

This generates a list of elements where member1 equals val.

For more examples, I'll refer to this package: http://download.java.net/jdk8/docs/api/java/util/stream/package-summary.html

If Java 8 is not available, then you have to resort to using simple for loops (or downloading a library to do this for you).

Upvotes: 2

Related Questions