title: Sort list based on specific order in java
body: <p>I have a list of object and need to sort it based on specific order. Something like below code:</p>
  
  <pre><code>preOrderedList = {"bmw","audi","benz"};
  </code></pre>
  
  <p>The list which comes from UI is carList <code>{"audi","benz","bmw"}</code>.</p>
  
  <p>Problem here is user will be able to add a new row from application. Suppose if user adds a new row of "audi", then the carList will be like
   <code>{"audi","benz","bmw","audi"}</code>. In this case the list should be sorted like <code>{"bmw","audi","audi","benz"}.</code></p>
  
  <p>I have tried below code. It works only for without adding a new row, means <code>{"audi","benz","bmw"}</code>.</p>
  
  <p><strong>That too while it gets sorts only the name("bmw","audi","benz") position is getting changed. I have one more field in Car class which is quantity. quantity will be in same position. This position should also get changed along with name.</strong></p>
  
  <pre><code>final List&lt;String&gt; preOrderedList = Arrays.asList("bmw","audi","benz");
  
  Collections.sort(carList, new Comparator&lt;Car&gt;() {
          public int compare(Car l1, Car l2) {
              if (preOrderedList.contains(l1.getName().trim()) &amp;&amp; preOrderedList.contains(l2.getName().trim())) {
                  return preOrderedList.indexOf(l1.getName().trim()) - preOrderedList.indexOf(l2.getName().trim());
              }
              if (preOrderedList.contains(l1.getName().trim())) {
                  return -1;
              }
              if (preOrderedList.contains(l2.getName().trim())) {
                  return 1;
              }
              return l1.getName().trim().toString().compareTo(l2.getName().trim().toString());
          }
      });
  </code></pre>
  
  <p>I Expect the output as <code>{"bmw","audi","audi","benz"}</code> but my actual output is <code>{"bmw","audi","benz","audi"}.</code></p>