io.datarouter.scanner.ScannerToGroups Maven / Gradle / Ivy
/*
* Copyright © 2009 HotPads ([email protected])
*
* Licensed 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 io.datarouter.scanner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class ScannerToGroups,M extends Map> implements Function,M>{
private final Function keyFunction;
private final Function valueFunction;
private final Supplier mapSupplier;
private final Supplier collectionSupplier;
private ScannerToGroups(
Function keyFunction,
Function valueFunction,
Supplier mapSupplier,
Supplier collectionSupplier){
this.keyFunction = keyFunction;
this.valueFunction = valueFunction;
this.mapSupplier = mapSupplier;
this.collectionSupplier = collectionSupplier;
}
@Override
public M apply(Scanner scanner){
M map = mapSupplier.get();
scanner.forEach(item -> {
K key = keyFunction.apply(item);
C collection = map.computeIfAbsent(key, $ -> collectionSupplier.get());
V value = valueFunction.apply(item);
collection.add(value);
});
return map;
}
/*--------------- Factories ----------------*/
public static
Function,Map>> of(
Function keyFunction){
return new ScannerToGroups<>(keyFunction, Function.identity(), HashMap::new, ArrayList::new);
}
public static
Function,Map>> of(
Function keyFunction,
Function valueFunction){
return new ScannerToGroups<>(keyFunction, valueFunction, HashMap::new, ArrayList::new);
}
public static >>
Function,M> of(
Function keyFunction,
Function valueFunction,
Supplier mapSupplier){
return new ScannerToGroups<>(keyFunction, valueFunction, mapSupplier, ArrayList::new);
}
public static ,M extends Map>
Function,M> of(
Function keyFunction,
Function valueFunction,
Supplier mapSupplier,
Supplier collectionSupplier){
return new ScannerToGroups<>(keyFunction, valueFunction, mapSupplier, collectionSupplier);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy