0

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?

Community
  • 1
  • 1
Andi Keikha
  • 1,246
  • 2
  • 16
  • 37

1 Answers1

2

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).

Ghostkeeper
  • 2,830
  • 1
  • 15
  • 27
  • java.util.stream is not in my system libraries, should I download it from somewhere and add it? sorry I couldn't find its download link. – Andi Keikha Mar 24 '14 at 19:01
  • 1
    Which version of Java do you have? This stuff is Java 8. – Dawood ibn Kareem Mar 24 '14 at 19:01
  • Ok, I will check that. I have recently installed eclipse, and this is my first program in java. I'm not sure. Thank you, this seems very similar to linq. – Andi Keikha Mar 24 '14 at 19:05
  • I am using this stream, but I don't need to import java.util.stream.* in my project, when I hover over the stream() function, it shows java.util.collection.stream(), I want to make sure that I am using it correctly. because my program seems to take for ever to be completed. – Andi Keikha Mar 26 '14 at 15:56