4

for example if i have

ArrayList<Product> productlist = new ArrayList<Product> ();

how do you get all the products which product.code equals to 1 and 2?

is there a library which can i use?

in c# i could use

productlist.where(product=> product.code.contains(arraywithproductcode)).ToList();

or other way was using

var newlist=(from p in productlist join a in arraywithproduct on a.product equals a select p);

how can i get it in java for android?

angel
  • 4,474
  • 12
  • 57
  • 89

4 Answers4

2

No lambda expressions in Android (or Java) yet.

You might want to see these options (haven't tested them in Android though):

Also, see this DZone link and this one. A stackoverflow post mentions this.

Update:

Lambda expression are now available in Java SE 8 For more information visit:

Lambda Expressions

Community
  • 1
  • 1
MiStr
  • 1,193
  • 10
  • 17
1

As shown in this introductory article Java 8 Stream on Android — Medium, there are two gems that seem to play really nicely together to provide the kind of LINQ-like experience you're asking for.

These are called retrolambda and Stream.

Added bonus, they don't need Java 8, so using them is compatible with old versions of Android.

Your C# code:

productlist
.where(product=> product.code.contains(arraywithproductcode))
.ToList();

Would turn to something like this:

productlist
.filter(product -> product.code.contains(arraywithproductcode))
.collect(Collectors.toList());

With the usual remark: "Do you really need to turn it into a list at the end? Perhaps the lazily-evaluated stream is what you actually want."

For other examples, use aNNiMON/Android-Java-8-Stream-Example: Demo app of using Java 8 features with Retrolambda and Lightweight-Stream-API

We use that here with Android Studio, but I would be surprised if it did not work with Eclipse.

Stéphane Gourichon
  • 6,493
  • 4
  • 37
  • 48
0

Depending on your use case you could either create a new list, iterate over the old one and add the ones matching your criteria to your new list.

If you want to avoid that and can live with the limitations of Guavas Collections2.filter() method, you can do this:

Collection<Product> filtered = Collections2.filter(productlist, new Predicate<Product>() {
    @Override
    public boolean apply(Product p) {
        return p.code == 1 || p.code == 2;
    }
});
jlordo
  • 37,490
  • 6
  • 58
  • 83
0

Maybe you could try this Java library: https://code.google.com/p/qood/

It handles data without any getter/setters, so it's more flexible than LINQ.

in your Product case, it might looks like:

final String[] productCodeArray = { ... };
final QModel products = ...; //QModel {PROD_CODE, PROD_FIELD1, PROD_FIELD2, ...}
final QModel filtered = products.query()
  .where(QNew.<String>whereIn("PROD_CODE").values(productCodeArray))
  .result().debug(-1);
schsu01
  • 1
  • 1