• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 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.cobalt.collect;
18 
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableListMultimap;
21 import com.google.common.collect.ImmutableMap;
22 
23 import java.util.function.Function;
24 import java.util.stream.Collector;
25 
26 /** Helper functions for working with immutable collections. */
27 public final class ImmutableHelpers {
ImmutableHelpers()28     private ImmutableHelpers() {}
29 
30     /** Collector to create immutable lists. */
toImmutableList()31     public static <T> Collector<T, ?, ImmutableList<T>> toImmutableList() {
32         return Collector.of(
33                 ImmutableList.Builder<T>::new,
34                 (l, v) -> l.add(v),
35                 (l1, l2) -> l1.addAll(l2.build()),
36                 ImmutableList.Builder::build);
37     }
38 
39     /** Collector to create immutable maps. */
toImmutableMap( Function<? super T, ? extends K> keyMap, Function<? super T, ? extends V> valueMap)40     public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
41             Function<? super T, ? extends K> keyMap, Function<? super T, ? extends V> valueMap) {
42         return Collector.of(
43                 ImmutableMap.Builder<K, V>::new,
44                 (m, e) -> m.put(keyMap.apply(e), valueMap.apply(e)),
45                 (m1, m2) -> m1.putAll(m2.build()),
46                 ImmutableMap.Builder::build);
47     }
48 
49     /** Collector to create immutable list multimaps. */
toImmutableListMultimap( Function<? super T, ? extends K> keyMap, Function<? super T, ? extends V> valueMap)50     public static <T, K, V> Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
51             Function<? super T, ? extends K> keyMap, Function<? super T, ? extends V> valueMap) {
52         return Collector.of(
53                 ImmutableListMultimap.Builder<K, V>::new,
54                 (m, e) -> m.put(keyMap.apply(e), valueMap.apply(e)),
55                 (m1, m2) -> m1.putAll(m2.build()),
56                 ImmutableListMultimap.Builder::build);
57     }
58 }
59