001/*
002 * Copyright (C) 2016 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static java.util.Collections.emptyList;
021
022import com.google.common.annotations.GwtCompatible;
023import java.util.ArrayList;
024import java.util.List;
025import java.util.NoSuchElementException;
026import java.util.Optional;
027import java.util.stream.Collector;
028import javax.annotation.CheckForNull;
029import org.checkerframework.checker.nullness.qual.Nullable;
030
031/**
032 * Collectors not present in {@code java.util.stream.Collectors} that are not otherwise associated
033 * with a {@code com.google.common} type.
034 *
035 * @author Louis Wasserman
036 * @since 21.0
037 */
038@GwtCompatible
039@ElementTypesAreNonnullByDefault
040public final class MoreCollectors {
041
042  /*
043   * TODO(lowasser): figure out if we can convert this to a concurrent AtomicReference-based
044   * collector without breaking j2cl?
045   */
046  private static final Collector<Object, ?, Optional<Object>> TO_OPTIONAL =
047      Collector.of(
048          ToOptionalState::new,
049          ToOptionalState::add,
050          ToOptionalState::combine,
051          ToOptionalState::getOptional,
052          Collector.Characteristics.UNORDERED);
053
054  /**
055   * A collector that converts a stream of zero or one elements to an {@code Optional}.
056   *
057   * @throws IllegalArgumentException if the stream consists of two or more elements.
058   * @throws NullPointerException if any element in the stream is {@code null}.
059   * @return {@code Optional.of(onlyElement)} if the stream has exactly one element (must not be
060   *     {@code null}) and returns {@code Optional.empty()} if it has none.
061   */
062  @SuppressWarnings("unchecked")
063  public static <T> Collector<T, ?, Optional<T>> toOptional() {
064    return (Collector) TO_OPTIONAL;
065  }
066
067  private static final Object NULL_PLACEHOLDER = new Object();
068
069  private static final Collector<@Nullable Object, ?, @Nullable Object> ONLY_ELEMENT =
070      Collector.<@Nullable Object, ToOptionalState, @Nullable Object>of(
071          ToOptionalState::new,
072          (state, o) -> state.add((o == null) ? NULL_PLACEHOLDER : o),
073          ToOptionalState::combine,
074          state -> {
075            Object result = state.getElement();
076            return (result == NULL_PLACEHOLDER) ? null : result;
077          },
078          Collector.Characteristics.UNORDERED);
079
080  /**
081   * A collector that takes a stream containing exactly one element and returns that element. The
082   * returned collector throws an {@code IllegalArgumentException} if the stream consists of two or
083   * more elements, and a {@code NoSuchElementException} if the stream is empty.
084   */
085  @SuppressWarnings("unchecked")
086  public static <T extends @Nullable Object> Collector<T, ?, T> onlyElement() {
087    return (Collector) ONLY_ELEMENT;
088  }
089
090  /**
091   * This atrocity is here to let us report several of the elements in the stream if there were more
092   * than one, not just two.
093   */
094  private static final class ToOptionalState {
095    static final int MAX_EXTRAS = 4;
096
097    @CheckForNull Object element;
098    List<Object> extras;
099
100    ToOptionalState() {
101      element = null;
102      extras = emptyList();
103    }
104
105    IllegalArgumentException multiples(boolean overflow) {
106      StringBuilder sb =
107          new StringBuilder().append("expected one element but was: <").append(element);
108      for (Object o : extras) {
109        sb.append(", ").append(o);
110      }
111      if (overflow) {
112        sb.append(", ...");
113      }
114      sb.append('>');
115      throw new IllegalArgumentException(sb.toString());
116    }
117
118    void add(Object o) {
119      checkNotNull(o);
120      if (element == null) {
121        this.element = o;
122      } else if (extras.isEmpty()) {
123        // Replace immutable empty list with mutable list.
124        extras = new ArrayList<>(MAX_EXTRAS);
125        extras.add(o);
126      } else if (extras.size() < MAX_EXTRAS) {
127        extras.add(o);
128      } else {
129        throw multiples(true);
130      }
131    }
132
133    ToOptionalState combine(ToOptionalState other) {
134      if (element == null) {
135        return other;
136      } else if (other.element == null) {
137        return this;
138      } else {
139        if (extras.isEmpty()) {
140          // Replace immutable empty list with mutable list.
141          extras = new ArrayList<>();
142        }
143        extras.add(other.element);
144        extras.addAll(other.extras);
145        if (extras.size() > MAX_EXTRAS) {
146          extras.subList(MAX_EXTRAS, extras.size()).clear();
147          throw multiples(true);
148        }
149        return this;
150      }
151    }
152
153    Optional<Object> getOptional() {
154      if (extras.isEmpty()) {
155        return Optional.ofNullable(element);
156      } else {
157        throw multiples(false);
158      }
159    }
160
161    Object getElement() {
162      if (element == null) {
163        throw new NoSuchElementException();
164      } else if (extras.isEmpty()) {
165        return element;
166      } else {
167        throw multiples(false);
168      }
169    }
170  }
171
172  private MoreCollectors() {}
173}