转载请注明出处。
package com.sdzxl.jeasy.common.collection;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class MatchUtil {
/**
*
* @param left
* @param right
* @param keyMapper
* @return
*/
public static <E, K> List<E> keyAnyMatch(final Collection<E> left, final Collection<E> right, Function<E, K> keyMapper) {
Objects.requireNonNull(left);
Objects.requireNonNull(right);
Objects.requireNonNull(keyMapper);
Set<K> set = right.stream().map(keyMapper).collect(Collectors.toSet());
return left.stream().filter(e -> set.contains(keyMapper.apply(e))).collect(Collectors.toList());
}
/**
*
* @param left
* @param right
* @param keyMapper
* @return
*/
public static <E, K> List<E> keyNonMatch(final Collection<E> left, final Collection<E> right, Function<E, K> keyMapper) {
Objects.requireNonNull(left);
Objects.requireNonNull(right);
Objects.requireNonNull(keyMapper);
Set<K> set = right.stream().map(keyMapper).collect(Collectors.toSet());
return left.stream().filter(e -> !set.contains(keyMapper.apply(e))).collect(Collectors.toList());
}
/**
*
* @param left
* @param right
* @param keyMapper
* @param valMapper
* @return
*/
public static <E, K, V> List<E> valAnyMatch(final Collection<E> left, final Collection<E> right,
Function<E, K> keyMapper, Function<E, V> valMapper) {
Objects.requireNonNull(left);
Objects.requireNonNull(right);
Objects.requireNonNull(keyMapper);
Objects.requireNonNull(valMapper);
Map<K, V> map = new HashSet<>(right).stream().collect(Collectors.toMap(keyMapper, valMapper));
return left.stream()
.filter(e -> map.containsKey(keyMapper.apply(e))
&& Objects.equals(map.get(keyMapper.apply(e)), valMapper.apply(e)))
.collect(Collectors.toList());
}
/**
*
* @param left
* @param right
* @param keyMapper
* @param valMapper
* @return
*/
public static <E, K, V> List<E> valNonMatch(final Collection<E> left, final Collection<E> right,
Function<E, K> keyMapper, Function<E, V> valMapper) {
Objects.requireNonNull(left);
Objects.requireNonNull(right);
Objects.requireNonNull(keyMapper);
Objects.requireNonNull(valMapper);
Map<K, V> map = new HashSet<>(right).stream().collect(Collectors.toMap(keyMapper, valMapper));
return left.stream()
.filter(e -> map.containsKey(keyMapper.apply(e))
&& !Objects.equals(map.get(keyMapper.apply(e)), valMapper.apply(e)))
.collect(Collectors.toList());
}
}