Java generics - Sublist method

By YopY on Monday 3 January 2011 13:00 - Comments (5)
Category: -, Views: 4.664

Short random post.

Sometimes you have a list, and you want to retrieve a specific sublist out of that one, for example to filter out empty list elements or to get a list of values that matches a condition. You could write a method like this for every list you have - here's one to filter blank, empty or null strings out of a List of strings, for example:


Java:
1
2
3
4
5
6
7
8
9
public static List<String> filterEmptyStrings(List<String> input) {
    List<String> output = new ArrayList<String>(input.size());
    for (String s : input) {
        if (s != null && !"".equals(s.trim())) {
            output.add(s);
        }
    }
    return output;
}



This'll get tedious in the long run though, as you'll need to create a new method for every object type you want to filter in every way. Java Generics to the rescue!


Java:
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface SublistCondition<T> {
    public boolean matches(T inputObject);
}

public static <T> List<T> subList(List<T> input, SublistCondition<T> condition) {
    List<T> result = new ArrayList<T>(input.size());
    for (T value : input) {
        if (condition.matches(value)) {
            result.add(value);
        }
    }
    return result;
}



Example usage, same result as the first example:


Java:
1
2
3
4
5
6
7
public static List<String> filterEmptyStrings(List<String> input) {
    return subList(input, new SublistCondition<String>() {
        public boolean matches(String input) {
            return input != null && !"".equals(input.trim());
        }
    });
}



It's not that much less code in this example, but you could move this particular SublistCondition into a separate object, so you can use it in every place you want to filter empty strings from a list:


Java:
1
2
3
public static List<String> filterEmptyStrings(List<String> input) {
    return subList(input, ListUtils.EmptyStringSublistCondition());
}

Volgende: Quick tryouts: Websockets 01-'11 Quick tryouts: Websockets
Volgende: JavaFX Taalfeatures - Kekke serietitel dag 2 07-'10 JavaFX Taalfeatures - Kekke serietitel dag 2

Comments


By Tweakers user Neverwinterx, Monday 3 January 2011 13:34

And here's what the usage would be like (more or less) with the lambda feature of Java 8:


code:
1
2
3
public static List<String> filterEmptyStrings(List<String> list) {
    return subList(list, # { String input -> input != null && !"".equals(input.trim()) } )
}



(Syntax is provisional and will change.)

[Comment edited on Monday 3 January 2011 13:38]


By Tweakers user [ti], Monday 3 January 2011 13:43

C# FTW:


code:
1
var resultList = inputList.Where(s => !string.IsNullOrEmpty(s));


By Tweakers user YopY, Monday 3 January 2011 13:47

Yes, I'd much prefer lambdas for things like this too. But until then, I guess this'll have to do. Java 8 is still years away, and widespread support will probably take even longer.

Although I'm sure there's other languages that run on the JVM, like Groovy or Clojure, that have these features by default (and that run on Java 1.4/5/6)

[Comment edited on Monday 3 January 2011 13:47]


By Tweakers user Nick_S, Monday 3 January 2011 14:10

Googles Guava (or the old Collections) has this build and calls it Filter which act on a Predicate instead of a SublistConstraint.

By Tweakers user YopY, Monday 3 January 2011 15:42

Nick_S wrote on Monday 03 January 2011 @ 14:10:
Googles Guava (or the old Collections) has this build and calls it Filter which act on a Predicate instead of a SublistConstraint.
I forgot to add a remark that this functionality was probably implemented in half a dozen publically available frameworks and libraries, ;). The Filter / Predicate naming is probably a more accurate one, or at least more relevant to a specific domain - functional programming, perchance?

And yes, dear readers, please don't copy-pasta these methods unless you really have to, in all other cases, use a library, those are written and maintained by people much smarter than me.

Comments are closed