Here is an object-oriented solution, a class called Mapper<S,T> , which displays values of any type that implements targets comparable to any type.
Syntax:
Mapper<String, Integer> mapper = Mapper.from("a","b","c").to(1,2,3); // Map a single value System.out.println(mapper.map("beef")); // 2 // Map a Collection of values System.out.println(mapper.mapAll( Arrays.asList("apples","beef","lobster"))); // [1, 2, 3]
The code:
public class Mapper<S extends Comparable<S>, T> { private final S[] source; private final T[] target;
Edit: finally replaced the map () method with a more efficient (and shorter) version. I know: the version that is looking for partitions will still be faster for large arrays, but sorry: I'm too lazy.
If you think this is too bloated, think about it:
- It contains a builder that allows you to create a mapper using the varargs syntax. I would say that it is mandatory for ease of use
- It contains both a single element and a collection matching method.
- It is a constant and therefore safe flow.
Of course, all these functions can be easily removed, but the code will be less complete, less useful or less stable.
Sean Patrick Floyd Sep 24 '10 at 15:19 2010-09-24 15:19
source share