3

Right now I am using a forloop to filter a list like so

LinkedList < classABC > filteredList = new LinkedList < > ();
for (ClassABC classABC: classABCList) {
 if (classABC.getName() == "ABC" && classABC.before(timestamp1)) {
  filteredList.add(classABC)
 } else if (classABC.before(timestamp2)) {
  filteredList.add(classABC)
 }
}
return filteredList

I was wondering if I could use a stream().filter() to do the same. I tried filter using multiple logical expressions but could not get it to work for compound logical expressions like (a && b) || (c)

Holger
  • 285,553
  • 42
  • 434
  • 765
Imprfectluck
  • 654
  • 6
  • 26
  • `(a && b) || (c)` is exactly what your code is doing so if that doesn't work there is some other problem. – Radiodef Apr 10 '16 at 01:36
  • I was jus explaining it more clearly.breaking down my code a bit. maybe i do not know if there is some way to use filter, BAsically i am asking if filter can be used for compund expressions or only for simple expressions. – Imprfectluck Apr 10 '16 at 01:38
  • A filter predicate is just a method accepting an element in the stream and returning a boolean. You can do anything you want in the predicate.....you could download a file in the predicate if you wanted. (Would it be a good idea? Maybe not. Is it possible? Totally.) `filter(abc -> (abc.getName() == "ABC" && abc.before(timestamp1)) || abc.before(timestamp2))` is exactly the same as your loop logic, because you do the same thing in your `if` block that you do in the `if else` block. – Radiodef Apr 10 '16 at 01:44
  • Side note: you shouldn't use `==` to compare Strings in Java. http://stackoverflow.com/q/513832/2891664 – Radiodef Apr 10 '16 at 01:45
  • I know its the same logic. and for loops are little bit better .filter(abc -> (abc.getName() == "ABC" && abc.before(timestamp1)) || abc.before(timestamp2)). But this does not work. – Imprfectluck Apr 10 '16 at 01:47
  • 1
    Syntactically, it will compile ([see ideone example](http://ideone.com/vYRoix)). If by "does not work" you mean there is some unexpected result, then you will need to show us a [minimal example](http://stackoverflow.com/help/mcve) and tell us what the problem is. – Radiodef Apr 10 '16 at 01:57
  • weird . it throws a syntax error for me. Thanks for the example. I will see if there is some other error(like if i screwed my brackets ). You might want to add that as an answer. Thanks – Imprfectluck Apr 10 '16 at 02:02
  • Instead of `== "ABC"` do `.equals("ABC")`. – Joop Eggen Apr 12 '16 at 19:01

1 Answers1

0

As it seems Stream filter can handle compound logical expressions. So I converted the if else like so.

filteredList = classABCList.stream()
             .filter(abc ->(abc.getName() == "ABC" && abc.before(timestamp1))
                    || abc.before(timestamp2)
             ).collect(toList());

Here is an ideone example suggested by RadioDef(Thanks for the example!)

Example

Imprfectluck
  • 654
  • 6
  • 26