Skip to content

Instantly share code, notes, and snippets.

@lfborjas
Created February 8, 2011 23:12
Show Gist options
  • Save lfborjas/817504 to your computer and use it in GitHub Desktop.
Save lfborjas/817504 to your computer and use it in GitHub Desktop.
Filter even numbers in a list; fork it for maximum fun!
#these are meant to be run in a REPL, and the java one in beanshell of something of the sort:
#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])
#but we don't need the wrapper (thanks to the guys in hackernews:)
(filter even? [1 2 3 4])
#scheme
(filter (lambda (x) (even? x)) '(1 2 3 4))
#same here:
(filter even? '(1 2 3 4))
#common lisp
(remove-if-not (lambda (x) (evenp x)) '(1 2 3 4))
#and here:
(remove-if-not 'evenp '(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);
}
}}
);
}
}
#After reading comments here and on HN, I now see that trying to *remove* stuff (filter-out) in hopes
#of mimicking how it _looks_ in other languages is stupid, even the lisps are actually building a new list
#recursively, so, here's a java version (which I took from the commments below) which is much more
#idiomatic and fair, as it accomplishes the same as the others: not using more than one explicit variable, #and that one, bound:
public class filter {
public static void main (String [] args)
{
System.out.println(
new java.util.ArrayList(){{
for(Integer e : new Integer[]{1,2,3,4})
if(e%2 == 0) this.add(e);
}}
);
}
}
@rep-movsd
Copy link

More succinct C++ version

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

int main (void)
{
    int nums[] = {1,2,3,4};
    remove_copy_if(nums, nums + 4, ostream_iterator<int>(cout, " "), [](int x) {return x % 2;});
    return 0;
}

@embuc
Copy link

embuc commented Nov 21, 2016

Oh, well:

Java:

Arrays.asList(1,2,3,4).stream().filter((i)-> i%2==0).collect(toList());

@GraniteConsultingReviews

I have a problem in a loop while compiling this code giving error in this portion

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