1 /*
2  * Copyright (C) 2021 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 com.android.permission.util;
18 
19 import android.annotation.Nullable;
20 
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.Map;
24 
25 /**
26  * {@link Collection} utilities.
27  */
28 public class CollectionUtils {
CollectionUtils()29     private CollectionUtils() {}
30 
31     /**
32      * Get the first element of a {@link List}, or {@code null} if none.
33      *
34      * @param list the {@link List}, or {@code null}
35      * @param <E> the element type of the {@link List}
36      * @return the first element of the {@link List}, or {@code 0} if none
37      */
38     @Nullable
firstOrNull(@ullable List<E> list)39     public static <E> E firstOrNull(@Nullable List<E> list) {
40         return !isEmpty(list) ? list.get(0) : null;
41     }
42 
43     /**
44      * Check whether a {@link Collection} is empty or {@code null}.
45      *
46      * @param collection the {@link Collection}, or {@code null}
47      * @return whether the {@link Collection} is empty or {@code null}
48      */
isEmpty(@ullable Collection<?> collection)49     public static boolean isEmpty(@Nullable Collection<?> collection) {
50         return collection == null || collection.isEmpty();
51     }
52 
53     /**
54      * Get the size of a {@link Collection}, or {@code 0} if {@code null}.
55      *
56      * @param collection the {@link Collection}, or {@code null}
57      * @return the size of the {@link Collection}, or {@code 0} if {@code null}
58      */
size(@ullable Collection<?> collection)59     public static int size(@Nullable Collection<?> collection) {
60         return collection != null ? collection.size() : 0;
61     }
62 
63     /**
64      * Get the size of a {@link Map}, or {@code 0} if {@code null}.
65      *
66      * @param collection the {@link Map}, or {@code null}
67      * @return the size of the {@link Map}, or {@code 0} if {@code null}
68      */
size(@ullable Map<?, ?> collection)69     public static int size(@Nullable Map<?, ?> collection) {
70         return collection != null ? collection.size() : 0;
71     }
72 }
73