1

I have created a class called Pair which is a generic type of L and R which would basically allow me to store pairs.

I am using an Arraylist to store the type Pair but I am not sure how to sort (and potentially search all elements) the arraylist based on the key/value and also print the ArrayList.

    ArrayList<Pair> a = new ArrayList<Pair>();

    Pair p = new Pair(1,1);
    a.add(p);
    a.add(new Pair(1,3));

    //System.out.println(help please);

Below is the Pair Class

class Pair<L,R> {

        L left;
        R right;

      public Pair(L left, R right) {
        this.left = left;
        this.right = right;
      }

      public L getLeft() { return left; }
      public R getRight() { return right; }

      @Override
      public int hashCode() { return left.hashCode() ^ right.hashCode(); }

      @Override
      public boolean equals(Object o) {
        if (!(o instanceof Pair)) return false;
        Pair pairo = (Pair) o;
        return this.left.equals(pairo.getLeft()) &&
               this.right.equals(pairo.getRight());
      }




    }
2
  • Does declaring an ArrayList containing raw Pair instances cause trouble for you? Have you compiled? Commented Mar 19, 2015 at 11:21
  • You are using an awful lot of raw types here: Pair instead of Pair<Integer, Integer>, for instance. You should really fix this so the you have type safety. Commented Mar 19, 2015 at 12:05

4 Answers 4

3

Here's a working code example for you (it's using some Java 8 features but these can be swapped out if you're restricted to a lower version). Hope this helps!

Thanks, Duncan

package com.hiveit;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Pair<L extends Comparable<L>, R extends Comparable<R>> implements Comparable<Pair<L, R>> {

  L left;
  R right;

  public Pair(final L left, final R right) {
    this.left = left;
    this.right = right;
  }

  public L getLeft() {
    return left;
  }

  public R getRight() {
    return right;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (left == null ? 0 : left.hashCode());
    result = prime * result + (right == null ? 0 : right.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final Pair<?, ?> other = (Pair<?, ?>) obj;
    if (left == null) {
      if (other.left != null) {
        return false;
      }
    } else if (!left.equals(other.left)) {
      return false;
    }
    if (right == null) {
      if (other.right != null) {
        return false;
      }
    } else if (!right.equals(other.right)) {
      return false;
    }
    return true;
  }

  @Override
  public int compareTo(final Pair<L, R> other) {

    final int compareLeft = left.compareTo(other.left);

    if (compareLeft != 0) {
      return compareLeft;
    }

    return right.compareTo(other.right);
  }

  @Override
  public String toString() {
    return "Pair [left=" + left + ", right=" + right + "]";
  }

  public static String listToString(final List<?> list) {
    return list.stream().map((pair) -> {
      return pair.toString();
    }).collect(Collectors.joining(", "));
  }

  public static void main(final String[] args) {

    final List<Pair<Integer, Integer>> a = new ArrayList<>();

    a.add(new Pair<>(1, 1));
    a.add(new Pair<>(2, 1));
    a.add(new Pair<>(2, 3));
    a.add(new Pair<>(1, 2));
    a.add(new Pair<>(1, 3));
    a.add(new Pair<>(2, 2));

    final List<Pair<Integer, Integer>> sortedByKey = new ArrayList<>(a);
    sortedByKey.sort((o1, o2) -> {
      return o1.getLeft().compareTo(o2.getLeft());
    });

    sortedByKey.stream().map((pair) -> {
      return pair.toString();
    }).collect(Collectors.joining(", "));

    final List<Pair<Integer, Integer>> sortedByValue = new ArrayList<>(a);
    sortedByValue.sort((o1, o2) -> {
      return o1.getRight().compareTo(o2.getRight());
    });

    final List<Pair<Integer, Integer>> sortedByKeyAndValue = new ArrayList<>(a);
    sortedByKeyAndValue.sort((o1, o2) -> {
      return o1.compareTo(o2);
    });

    System.out.println("Original                  = " + listToString(a));
    System.out.println("Sorted by Left            = " + listToString(sortedByKey));
    System.out.println("Sorted by Right           = " + listToString(sortedByValue));
    System.out.println("Sorted by Left then Right = " + listToString(sortedByKeyAndValue));

  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thank you for taking the time to answer my question. Really appreciate it.
3

Your Pair class could for example implement Comparator<Pair> interface. After that you implement the method

@Override
public int compare(Pair o1, Pair o2) {
    // here you need to implement how one Pair can be compared to another
    // in the scope of ordering them
    // you need to fulfil the contract of the Comparator.compare interface
}

Comments

2

The Collections API provides are sort utility for this.

http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

You simply need to write a class to implement a Comparator for your Pair class.

Comments

0

Don't use your Pair class. If what you need is a sorted, traversable and efficient collection of key/value pairs with generic types use a TreeMap.

4 Comments

Also, your code doesn't like like it compiles to me. For instance, the first declaration should be ArrayList<Pair<Integer, Integer> > a = new ArrayList<Pair<Integer, Integer> >();. You can also use type inference if you are on Java 8.
Using TreeMap won't be able to handle the case where there are multiple pairs with the same left value. It's not the same thing.
Very true! But he did mention key/value. The concept itself is that keys are unique and point to a value. So if he really just want an array of tuples, you are right, but if he wants key/value I'm pointing him in the right direction. Hard to tell how familiar he is with the topic or what his actual problem is, but given that sorting and comparators are fairly basic (and he didn't came up with them), I think it was good I mention this.
Tree map would not work for me as I need duplicate key value pairs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.