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