001package ball.util; 002/*- 003 * ########################################################################## 004 * Utilities 005 * $Id: Comparators.java 8366 2021-08-08 06:29:23Z 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 - 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.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: 8366 $ 032 */ 033@Deprecated 034public abstract class Comparators { 035 private Comparators() { } 036 037 /** 038 * Static method to return a {@link Comparator} ordering members in the 039 * same order as the {@link List}. 040 * 041 * @param list The {@link List} describing the order. 042 * @param <T> The type to be ordered. 043 * 044 * @return A {@link Comparator} enforcing the specified order. 045 */ 046 public static <T> Comparator<T> orderedBy(List<T> list) { 047 return new OrderedComparator<T>(list); 048 } 049 050 private static class OrderedComparator<T> extends HashMap<T,Integer> 051 implements Comparator<T> { 052 private static final long serialVersionUID = 4745150194266705710L; 053 054 public OrderedComparator(List<T> list) { 055 for (int i = 0, n = list.size(); i < n; i += 1) { 056 put(list.get(i), i); 057 } 058 } 059 060 @Override 061 public int compare(T left, T right) { 062 return Integer.compare(getOrDefault(left, -1), 063 getOrDefault(right, size())); 064 } 065 } 066}