All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hubspot.slack.client.enums.EnumIndex Maven / Gradle / Ivy

package com.hubspot.slack.client.enums;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collector;

public class EnumIndex> {

  private final ImmutableMap index;
  private final Class enumType;

  public EnumIndex(Class enumType, Function keyExtractor) {
    index = Maps.uniqueIndex(EnumSet.allOf(enumType), keyExtractor::apply);
    this.enumType = enumType;
  }

  public V get(K key) throws UnmappedKeyException {
    return find(key).orElseThrow(() -> new UnmappedKeyException(enumType, key));
  }

  public Optional find(K key) {
    return Optional.ofNullable(index.get(key));
  }

  public ImmutableSet getUnmappedKeys(Collection keys) {
    return keys.stream().filter(key -> !index.containsKey(key)).collect(toImmutableSet());
  }

  public ImmutableSet getAllPresent(Collection keys) {
    return keys
      .stream()
      .map(this::find)
      .filter(Optional::isPresent)
      .map(Optional::get)
      .collect(toImmutableEnumSet());
  }

  private static  Collector, ImmutableSet> toImmutableSet() {
    return Collector.of(
      ImmutableSet.Builder::new,
      ImmutableSet.Builder::add,
      (left, right) -> left.addAll(right.build()),
      ImmutableSet.Builder::build
    );
  }

  public static > Collector, ImmutableSet> toImmutableEnumSet() {
    return Collector.of(
      HashSet::new,
      HashSet::add,
      (left, right) -> {
        left.addAll(right);
        return left;
      },
      Sets::immutableEnumSet
    );
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy