1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.tools.comparator;
16  
17  import java.util.Comparator;
18  import java.util.List;
19  
20  /**
21   * <a href="ColumnsComparator.java.html"><b><i>View Source</i></b></a>
22   *
23   * @author Brian Wing Shun Chan
24   */
25  public class ColumnsComparator implements Comparator<Object> {
26  
27      public ColumnsComparator(String columnName) {
28          this(new String[] {columnName});
29      }
30  
31      public ColumnsComparator(List<String> columnNames) {
32          this(columnNames.toArray(new String[columnNames.size()]));
33      }
34  
35      public ColumnsComparator(String[] columnNames) {
36          _columnNames = columnNames;
37      }
38  
39      public int compare(Object obj1, Object obj2) {
40          Object[] column1 = (Object[])obj1;
41          Object[] column2 = (Object[])obj2;
42  
43          String columnName1 = (String)column1[0];
44          String columnName2 = (String)column2[0];
45  
46          int x = -1;
47  
48          for (int i = 0; i < _columnNames.length; i++) {
49              if (_columnNames[i].equals(columnName1)) {
50                  x = i;
51  
52                  break;
53              }
54          }
55  
56          int y = -1;
57  
58          for (int i = 0; i < _columnNames.length; i++) {
59              if (_columnNames[i].equals(columnName2)) {
60                  y = i;
61  
62                  break;
63              }
64          }
65  
66          if ((x == -1) && (y > -1)) {
67              return 1;
68          }
69          else if ((x > -1) && (y == -1)) {
70              return -1;
71          }
72          else if ((x > -1) && (y > -1)) {
73              if (x < y) {
74                  return -1;
75              }
76              else if (x > y) {
77                  return 1;
78              }
79          }
80  
81          return 0;
82      }
83  
84      private String[] _columnNames;
85  
86  }