title: java sort list of objects by specifiable attribute
body: <p>I want to sort a List of objects by a specified attribute of those objects and I want to choose which attribute should be used for sorting. Example:  </p>
  
  <pre><code>class Car{
    private String name;
    private String colour;
    public enum sortBy {NAME, COLOUR};
  
    public String name(){
      return name;
    }
  
    public String colour(){
      return colour;
    }
  
    public static Car[] getSortedArray(Car[] carArray, sortBy sortType){
      HashMap&lt;Object, Car&gt; carMap = new HashMap&lt;Object, Car&gt;();
      Object[] sortArray = new Object[carArray.length];
      Object value = null;
      for(int i = 0; i &lt; carArray.length; i++){
        if(sortType == sortBy.NAME){
          value = carArray[i].name();
        }else if(sortType == sortBy.COLOUR){
          value = carArray[i].colour();
        }
        carMap.put(value, carArray[i]);
        sortArray[i] = value;
      }  
      Arrays.sort(sortArray);
      Car[] sortedArray = new Car[sortArray.length];
      for(int i = 0; i &lt; sortArray.length; i++){
        sortedArray[i] = carMap.get(sortArray[i]);
      }
      return sortedArray;
    }
  }
  
  //external:
  Car[] cars = getSomeCars();
  Car[] nameSortedCars = Car.getSortedArray(cars, Car.sortBy.NAME);
  Car[] colourSortedCars = Car.getSortedArray(cars, Car.sortBy.COLOUR);
  </code></pre>
  
  <p>The idea is simple:<br>
  I put all values that i want to sort by into an array, and i create a map that maps these values back to their objects. After I sorted this array I take the objects mapped to these values and put them in the same order into a new array which is then sorted by these values. The values are just created with type Object so I can sort by multiple types (not just Strings as in the example).</p>
  
  <p>This works fine unless you have two objects with the same attribute value, then only one object will be in the returned array, but two times.<br>
  Is there a better way to achieve this sorting?  </p>