简体   繁体   中英

Sorting Arraylist created using Generic Class in Java

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());
      }




    }

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
}

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));

  }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM