001package ball.util;
002/*-
003 * ##########################################################################
004 * Utilities
005 * $Id: Comparators.java 5285 2020-02-05 04:23:21Z ball $
006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-util/trunk/src/main/java/ball/util/Comparators.java $
007 * %%
008 * Copyright (C) 2008 - 2020 Allen D. Ball
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * ##########################################################################
022 */
023import java.util.Comparator;
024import java.util.HashMap;
025import java.util.List;
026
027/**
028 * {@link Comparator}s.
029 *
030 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
031 * @version $Revision: 5285 $
032 */
033public abstract class Comparators {
034    private Comparators() { }
035
036    /**
037     * Static method to return a {@link Comparator} ordering members in the
038     * same order as the {@link List}.
039     *
040     * @param   list            The {@link List} describing the order.
041     * @param   <T>             The type to be ordered.
042     *
043     * @return  A {@link Comparator} enforcing the specified order.
044     */
045    public static <T> Comparator<T> orderedBy(List<T> list) {
046        return new OrderedComparator<T>(list);
047    }
048
049    private static class OrderedComparator<T> extends HashMap<T,Integer>
050                                              implements Comparator<T> {
051        private static final long serialVersionUID = 4745150194266705710L;
052
053        public OrderedComparator(List<T> list) {
054            for (int i = 0, n = list.size(); i < n; i += 1) {
055                put(list.get(i), i);
056            }
057        }
058
059        @Override
060        public int compare(T left, T right) {
061            return Integer.compare(getOrDefault(left, -1),
062                                   getOrDefault(right, size()));
063        }
064    }
065}