Comparable with a sorted collection. : TreeSet « Collections Data Structure « Java






Comparable with a sorted collection.

  

import java.util.Set;
import java.util.TreeSet;

class Product implements Comparable<Product> {
  String prodName;

  int prodID;

  Product(String str, int id) {
    prodName = str;
    prodID = id;
  }

  public int compareTo(Product p2) {
    return prodName.compareToIgnoreCase(p2.prodName);
  }

  public boolean equals(Object p2) {
    return prodName.compareToIgnoreCase(((Product) p2).prodName) == 0;
  }
}

public class Main {
  public static void main(String args[]) {
    Set<Product> prodList = new TreeSet<Product>();

    prodList.add(new Product("A", 13546));
    prodList.add(new Product("B", 04762));
    prodList.add(new Product("C", 12221));
    prodList.add(new Product("D", 44387));

    for (Product p : prodList)
      System.out.printf("%-14s ID: %d\n", p.prodName, p.prodID);
  }
}

   
    
  








Related examples in the same category

1.Add values to TreeSet
2.TreeSet, SortedSet and HashSet
3.Get Synchronized Set from Java TreeSet example
4.Check if a particular value exists in Java TreeSet example
5.Copy all elements of Java TreeSet to an Object Array Example
6.Get Head Set from Java TreeSet example
7.Get lowest and highest value stored in Java TreeSet
8.Get Size of Java TreeSet
9.Get Sub Set from Java TreeSet
10.Get Tail Set from Java TreeSet
11.Iterate through elements of Java TreeSet
12.Remove all elements from Java TreeSet
13.Remove specified element from Java TreeSet
14.Sort items in a Set
15.Loop and remove element from a TreeSet
16.Creating a Sorted Set
17.A TreeSet that ensures it never grows beyond a max size.