Response to Ted Neward's - Anonymous Generic Methods making things "just work"


I saw Ted Neward's message and answered the call. I think this is what he wants, but who knows, I don't really care for C#. But it took 10 minutes in IntelliJ to cook up what I think is the equivalent in Java code.

Update: user57 on codehaus found a cool screencast program, MovieGrab. Here is my screencasting debut (you'll probably need QT7): neward.mp4

Here you go Ted. This took me 10 minutes in IntelliJ, I only typed about 10% of it. I think its what you want:


package com.sampullara.neward;

import java.util.List;
import java.util.ArrayList;

public class SetUtils<T> {
    public List<T> project(List<T> list, Predicate<T> pred) {
        List<T> results = new ArrayList<T>();
        for (T t : list) {
            if (pred.check(t)) results.add(t);
        }
        return results;
    }
}

package com.sampullara.neward;

public interface Predicate<T> {
    public boolean check(T t);
}

package com.sampullara.neward;

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.age = age;
        this.setFirstName(firstName);
        this.setLastName(lastName);
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                '}';
    }
}

package com.sampullara.neward;

import java.util.List;
import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {
        Person cg = new Person("Cathi", "Gero", 35);
        Person tn = new Person("Ted", "Neward", 35);
        Person sg = new Person("Stephanie", "Gero", 12);
        Person mn = new Person("Michael", "Neward", 12);

        List<Person> list = new ArrayList<Person>();
        list.add(cg);
        list.add(tn);
        list.add(sg);
        list.add(mn);

        List<Person> newards =
            new SetUtils<Person>().project(list, new Predicate<Person>() {
                public boolean check(Person p) { if (p.getLastName().equals("Neward")) return true; else return false; }
            });
        for (Person p : newards)
            System.out.println(p);
    }
 }

Output:

Person{firstName='Ted', lastName='Neward', age=35}
Person{firstName='Michael', lastName='Neward', age=12}


Posted: Tue - November 8, 2005 at 09:38 PM           |


©