Home RSS feed

 

Readable list operations

My attempt at simplifying common (java.util.)list operations such as:

Lists.sort(list).ascendingBy().getFirstName()
Lists.sort(list).nullsFirstDescendingBy().getFirstName()
Lists.filter(list).accept("Erik").getFirstName()
Lists.filter(list).rejectLessThan(18).getAge()
Long total = Lists.sum(list).getCredit()
Lists.search(list).forValue("Erik").getFirstName() != null
int minScore = Lists.search(list).forSmallest().getScore()
int minScore = Lists.min(list).getScore()
Lists.forEach(list).setScore(0)
Lists.select(fromList, toList).acceptGreaterThan(30).getAge()
Lists.collect(persons, names).getName()
Lists.groupBy(inputList, resultMap).getAge()

I think this has some very readable and easy to use code. Compare these (no pun intended. sort of. sorry.) different ways of sorting:

Pure Java:

Collections.sort(list, new Comparator<Person>() {
	public int compare(Person o1, Person o2) {
		if (null == ...
		return o1.getAge() - o2.getAge();
	}
});

Google Guava:

List<Person> sorted = Ordering.natural().nullsFirst().onResultOf(
		new Function<Person, Integer>() {
	public Integer apply(Person person) {
		return person.getAge();
	}
}).sortedCopy(list);

Lambdaj:

List<Person> sorted = Lambda.sort(list, Lambda.on(Person.class).getAge()); // nulls?

Mine:

Lists.sort(list).nullsFirstAscendingBy().getAge();

Google Guava and Lambdaj are much more powerful and feature complete, but I think mine is nice in specific cases.

Download: lists-0.2.jar (Java 5, source included, MPL2).

Javadoc

Known limitations:

Tags: java

Created on Fri, 15 Nov 2013 21:00

blog comments powered by Disqus