001package ball.util;
002/*-
003 * ##########################################################################
004 * Utilities
005 * %%
006 * Copyright (C) 2021, 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.Arrays;
022import java.util.Comparator;
023import java.util.List;
024import java.util.Objects;
025
026/**
027 * {@link List}-Order {@link Comparator}.
028 *
029 * {@bean.info}
030 *
031 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
032 */
033public class ListOrderComparator<T> implements Comparator<T> {
034    private final List<T> list;
035
036    /**
037     * Construct a {@link Comparator} from the argument {@link List}.
038     *
039     * @param   list            The {@link List} with the elements in ranked
040     *                          order.
041     */
042    public ListOrderComparator(List<T> list) {
043        this.list = Objects.requireNonNull(list);
044    }
045
046    /**
047     * Construct a {@link Comparator} from the argument array.
048     *
049     * @param   array           The array with the elements in ranked
050     *                          order.
051     */
052    @SafeVarargs @SuppressWarnings({ "varargs" })
053    public ListOrderComparator(T... array) { this(Arrays.asList(array)); }
054
055    @Override
056    public int compare(T left, T right) { return rank(left) - rank(right); }
057
058    private int rank(T object) {
059        int index = list.indexOf(object);
060
061        return (index >= 0) ? index : list.size();
062    }
063}