1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.collections.comparators;
  17. import java.util.Comparator;
  18. import org.apache.commons.collections.Transformer;
  19. /**
  20. * Decorates another Comparator with transformation behavior. That is, the
  21. * return value from the transform operation will be passed to the decorated
  22. * {@link Comparator#compare(Object,Object) compare} method.
  23. *
  24. * @since Commons Collections 2.0 (?)
  25. * @version $Revision$ $Date$
  26. *
  27. * @see org.apache.commons.collections.Transformer
  28. * @see org.apache.commons.collections.comparators.ComparableComparator
  29. */
  30. public class TransformingComparator implements Comparator {
  31. /** The decorated comparator. */
  32. protected Comparator decorated;
  33. /** The transformer being used. */
  34. protected Transformer transformer;
  35. //-----------------------------------------------------------------------
  36. /**
  37. * Constructs an instance with the given Transformer and a
  38. * {@link ComparableComparator ComparableComparator}.
  39. *
  40. * @param transformer what will transform the arguments to <code>compare</code>
  41. */
  42. public TransformingComparator(Transformer transformer) {
  43. this(transformer, new ComparableComparator());
  44. }
  45. /**
  46. * Constructs an instance with the given Transformer and Comparator.
  47. *
  48. * @param transformer what will transform the arguments to <code>compare</code>
  49. * @param decorated the decorated Comparator
  50. */
  51. public TransformingComparator(Transformer transformer, Comparator decorated) {
  52. this.decorated = decorated;
  53. this.transformer = transformer;
  54. }
  55. //-----------------------------------------------------------------------
  56. /**
  57. * Returns the result of comparing the values from the transform operation.
  58. *
  59. * @param obj1 the first object to transform then compare
  60. * @param obj2 the second object to transform then compare
  61. * @return negative if obj1 is less, positive if greater, zero if equal
  62. */
  63. public int compare(Object obj1, Object obj2) {
  64. Object value1 = this.transformer.transform(obj1);
  65. Object value2 = this.transformer.transform(obj2);
  66. return this.decorated.compare(value1, value2);
  67. }
  68. }