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

com.intellij.openapi.util.Pair Maven / Gradle / Ivy

// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.util;

import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Comparator;

/**
 * Generic wrapper around two related values.
 */
public class Pair {
  public final A first;
  @Nls public final B second;

  @NotNull
  public static  Pair create(A first, B second) {
    return new Pair<>(first, second);
  }

  @NotNull
  public static  NonNull createNonNull(@NotNull A first, @NotNull B second) {
    return new NonNull<>(first, second);
  }

  @NotNull
  public static  Pair pair(A first, B second) {
    return new Pair<>(first, second);
  }

  public static  T getFirst(@Nullable Pair pair) {
    return pair != null ? pair.first : null;
  }

  public static  T getSecond(@Nullable Pair pair) {
    return pair != null ? pair.second : null;
  }

  @SuppressWarnings({"rawtypes", "unchecked"})
  private static final Pair EMPTY = create(null, null);

  @NotNull
  @SuppressWarnings("unchecked")
  public static  Pair empty() {
    return EMPTY;
  }

  /**
   * @see #create(Object, Object)
   */
  public Pair(A first, B second) {
    this.first = first;
    this.second = second;
  }

  public final A getFirst() {
    return first;
  }

  public final B getSecond() {
    return second;
  }

  @Override
  public final boolean equals(Object o) {
    return o instanceof Pair oo && Comparing.equal(first, oo.first) && Comparing.equal(second, oo.second);
  }

  @Override
  public int hashCode() {
    int result = first != null ? first.hashCode() : 0;
    result = 31 * result + (second != null ? second.hashCode() : 0);
    return result;
  }

  @Override
  public String toString() {
    return "<" + first + "," + second + ">";
  }

  public static class NonNull extends Pair {
    public NonNull(@NotNull A first, @NotNull B second) {
      super(first, second);
    }
  }

  /**
   * @param  first value type (Comparable)
   * @param  second value type
   * @return a comparator that compares pair values by first value
   */
  public static , B> Comparator> comparingByFirst() {
    return Comparator.comparing(o -> o.first);
  }

  /**
   * @param  first value type
   * @param  second value type (Comparable)
   * @return a comparator that compares pair values by second value
   */
  public static > Comparator> comparingBySecond() {
    return Comparator.comparing(o -> o.second);
  }
}