8

Let's see this example C# code:

List<int> numbers = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int numCount = numbers.Where(n => n < 3 || n > 7).Count();

I'm insterested in cloesest equivalent in Java, obviously without need to write fancy for/foreach loops to iterate in collection.

As far as I know, there is no exact linq equivalnet in Java, however I'm still beginner in Java programming, so is there anything you could recommend for me? I'm actually looking for most compact and elegant way to achieve the same result in Java

[added] So, thanks for all reponses. However, I need to use it on Android and it seem I can't. Is there any solution for that?

(sorry it it's duplicate)

[added] Have anybody tried this? http://sourceforge.net/projects/streamsupport/

user1209216
  • 7,404
  • 12
  • 60
  • 123
  • @caesay if you scroll down the answers you'll find out about `Java 8 streams` which will do the job here – Sybren Sep 18 '15 at 07:38
  • @Sybren: I'm one of the answers. I am suggesting a duplicate question. The question here is "how do i filter an array based on a predicate", which is also the question of the link i posted. – caesay Sep 18 '15 at 07:40
  • @Yes, the answer is in your link too but also in mine, so I don't understand why you disagree with my duplicate. – Sybren Sep 18 '15 at 07:42

4 Answers4

4

In Java8:

Arrays.stream(numbers).filter(n -> n < 3 || n > 7).count();

In response to your requirement for android, check out lambdaj: https://code.google.com/p/lambdaj/ It is compatible for android - although the syntax is different. You'll have to look at the documentation as i've never used it. You could also check out https://github.com/wagnerandrade/coollection

caesay
  • 16,932
  • 15
  • 95
  • 160
  • Lambdaj looks promising, it's not so clear as C# linq but it's more than nothing – user1209216 Sep 18 '15 at 07:52
  • I found Guava Collections + lambdas (or method reference) as the best solution for Android. Unfortunately, Java 8 stream api is not a solution, because it needs minimal api Android 7. Guava provides similar api, but it also works on any Android version. I can't answer my my question, because admin has decided to mark it as duplicate – user1209216 Jan 17 '18 at 10:45
3

If you need for Java 7 or earlier versions try lambdaj library available in google code. If not same it will give the similar functionality.

Tanveer Ali
  • 393
  • 3
  • 6
2

The Java 8 Streaming API in combination with Lambda Expressions will do the job:

    int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    long count = Arrays.stream(numbers).filter(n -> n < 3 || n > 7).count();
Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51
1

Using Java8 streams will work really similar:

int numcount = Arrays.stream(numbers).filter(n -> n < 3 || n > 7).count();
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109