1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.hardware.camera2.utils; 18 19 import java.util.List; 20 21 /** 22 * Various assortment of list utilities. 23 * 24 * <p>Using a {@code null} list is supported and will almost always return the default value 25 * (e.g. {@code false}, or {@code null}).</p> 26 */ 27 public class ListUtils { 28 29 /** Return {@code} true if the {@code list} contains the {@code needle}. */ listContains(List<T> list, T needle)30 public static <T> boolean listContains(List<T> list, T needle) { 31 if (list == null) { 32 return false; 33 } else { 34 return list.contains(needle); 35 } 36 } 37 38 /** 39 * Return {@code true} if the {@code list} is only a single element equal to 40 * {@code single}. 41 */ listElementsEqualTo(List<T> list, T single)42 public static <T> boolean listElementsEqualTo(List<T> list, T single) { 43 if (list == null) { 44 return false; 45 } 46 47 return (list.size() == 1 && list.contains(single)); 48 } 49 50 /** 51 * Return a human-readable representation of a list (non-recursively). 52 */ listToString(List<T> list)53 public static <T> String listToString(List<T> list) { 54 if (list == null) { 55 return null; 56 } 57 58 StringBuilder sb = new StringBuilder(); 59 sb.append('['); 60 61 int size = list.size(); 62 int i = 0; 63 for (T elem : list) { 64 sb.append(elem); 65 66 if (i != size - 1) { 67 sb.append(','); 68 } 69 i++; 70 } 71 sb.append(']'); 72 73 return sb.toString(); 74 } 75 76 /** 77 * Return the first item from {@code choices} that is contained in the {@code list}. 78 * 79 * <p>Choices with an index closer to 0 get higher priority. If none of the {@code choices} 80 * are in the {@code list}, then {@code null} is returned. 81 * 82 * @param list a list of objects which may or may not contain one or more of the choices 83 * @param choices an array of objects which should be used to select an item from 84 * 85 * @return the first item from {@code choices} contained in {@code list}, otherwise {@code null} 86 */ listSelectFirstFrom(List<T> list, T[] choices)87 public static <T> T listSelectFirstFrom(List<T> list, T[] choices) { 88 if (list == null) { 89 return null; 90 } 91 92 for (T choice : choices) { 93 if (list.contains(choice)) { 94 return choice; 95 } 96 } 97 98 return null; 99 } 100 ListUtils()101 private ListUtils() { 102 throw new AssertionError(); 103 } 104 } 105