GroupingByCollector.java
/*
* Copyright 2020 Collect Utils Authors
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package net.morimekta.collect.collectors;
import net.morimekta.collect.UnmodifiableList;
import net.morimekta.collect.UnmodifiableMap;
import net.morimekta.collect.UnmodifiableSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import static java.util.Objects.requireNonNull;
public class GroupingByCollector<E, K, V> implements Collector<E, Map<K, List<V>>, UnmodifiableMap<K, List<V>>> {
private final Function<E, K> toKey;
private final Function<E, V> toValue;
public GroupingByCollector(Function<E, K> toKey, Function<E, V> toValue) {
this.toKey = requireNonNull(toKey);
this.toValue = requireNonNull(toValue);
}
@Override
public Supplier<Map<K, List<V>>> supplier() {
return HashMap::new;
}
@Override
public BiConsumer<Map<K, List<V>>, E> accumulator() {
return (b, e) -> b
.computeIfAbsent(toKey.apply(e), k -> new ArrayList<>())
.add(toValue.apply(e));
}
@Override
public BinaryOperator<Map<K, List<V>>> combiner() {
return (b1, b2) -> {
for (Map.Entry<K, List<V>> entry : b2.entrySet()) {
b1.computeIfAbsent(entry.getKey(), k -> new ArrayList<>(entry.getValue().size()))
.addAll(entry.getValue());
}
return b1;
};
}
@Override
public Function<Map<K, List<V>>, UnmodifiableMap<K, List<V>>> finisher() {
return map -> {
UnmodifiableMap.Builder<K, List<V>> builder = UnmodifiableMap.newBuilder();
for (Map.Entry<K, List<V>> entry : map.entrySet()) {
builder.put(entry.getKey(), UnmodifiableList.asList(entry.getValue()));
}
return builder.build();
};
}
@Override
public Set<Characteristics> characteristics() {
return UnmodifiableSet.setOf();
}
}