title: Java Comparator given the name of the property to compare
body: <p>My problem is this; I have to order a table of data. Each row of the table is an object (lets call it TableObject) stored in a List. Each column of data is a property of the class (usually a String).</p>
  
  <p>I have to do the typical ordering of data when the user clicks on any column. So I thought about changing the List to a TreeSet and implementing Comparator in my TableObject.</p>
  
  <p>The problem comes when I try to reorder the TreeSet. The compare is fairly easy at first (cheeking for exceptions in parseInt have been omitted):</p>
  
  <pre><code>   public int compare(TableObject to1, TableObject to2){
          TableObject t1 = to1;
          TableObject t2 = to2;
  
          int result = 1;
  
          if(Integer.parseInt(t1.getId()) == Integer.parseInt(t2.getId())){result=0;}
          if(Integer.parseInt(t1.getId()) &lt; Integer.parseInt(t2.getId())){result=-1;}
  
          return result;
  
      }
  </code></pre>
  
  <p>But when I have to reorder by the text of the data or by other dozens of data that the TableObject has I have a problem.
  I do not want to create dozens of compare functions, each for one. I prefer not to use a switch (or a chain of ifs) to decide how to compare the object.</p>
  
  <p>Is there any way to do this in some way (like Reflexive), that doesn't imply that I will write like hundreds of lines of nearly the same code?</p>
  
  <p>Thanks for all!</p>