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