Skip to content

Instantly share code, notes, and snippets.

@kennethreitz
Forked from lfborjas/gist:817504
Created February 8, 2011 23:57
Show Gist options
  • Save kennethreitz/817570 to your computer and use it in GitHub Desktop.
Save kennethreitz/817570 to your computer and use it in GitHub Desktop.
#ruby
[1,2,3,4].select{ |x| x.even? }
#python
[x for x in [1,2,3,4] if not x%2]
#or, more norvingly
filter(lambda x: not x%2, [1,2,3,4])
#clojure
(filter #(even? % ) [1 2 3 4])
#scheme
(filter (lambda (x) (even? x)) '(1 2 3 4))
#common lisp
(remove-if-not (lambda (x) (evenp x)) '(1 2 3 4))
#javascript
[1,2,3,4].filter(function(x){return !(x%2)})
#java
import java.util.ArrayList;
import java.util.Arrays;
public class filter {
public static void main (String [] args)
{
Integer [] a = {1,2,3,4};
System.out.println(
new ArrayList<Integer>(Arrays.asList(a)){{
ArrayList<Integer> clon = (ArrayList<Integer>)this.clone();
for(Integer e : clon){
if(e.intValue()%2 != 0)
this.remove(e);
}
}}
);
}
}
@apetresc
Copy link

apetresc commented Feb 9, 2011

Or, if you're using Google's Guava library (which everyone should, and is likely to be rolled into JDK8), it's just:

Iterables.filter(
    Lists.newArrayList(1, 2, 3, 4),
    new Predicate<Integer>() { public boolean apply(Integer x) { return x % 2 == 0; } });

(Plus all the surrounding main stuff which it's no longer cool to criticize Java for requiring, as it's just not that big a deal).

@kennethreitz
Copy link
Author

You should comment here: https://gist.github.com/817504

@DanielHeath
Copy link

ruby

require 'activesupport'
[1,2,3,4].select &:even?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment