2016-03-03 40 views
0

我有一個對象列表(比如說Office對象),它具有像say ID,名稱,位置,強度等屬性。現在,假設,場地位置具有來自某個集合的值(例如,3個可能的值,紐約,加利福尼亞州,猶他州)。現在,我想重新安排位置屬性中的這個列表,使位置屬性爲紐約的Office對象在列表中排在第一位,然後在加利福尼亞州排在第一位,然後是猶他州。所以,基本上這不是升序或降序,而是我爲該財產設定的標準。在Java中實現這個最有效的方法是什麼?重新安排一個屬性的對象列表(不是升序/降序)

我首先想到使用Comprator,但我不想簡單地按照升序/降序排序,而是按照上面提到的標準進行排序。不知道,如果我可以使用COMBATOR這個以及如果是的話。如果不是,那麼另一種最有效的方法是什麼?

+0

'Collections.sort '可以有一個額外的比較器,您可以製作幾個或即時。 Java 8允許使用非常簡潔的符號,甚至可以組合比較器。 –

回答

0

簡單,不能排除與理想需要包含所有位置:

public static void rearrangeSort(List<Office> source, String... locations) { 
    List<String> locs = Arrays.asList(locations); 
    Collections.sort(source, (o1, o2) -> locs.indexOf(o1.getLocation()) - locs.indexOf(o2.getLocation())); 
} 

更復雜:

public static List<Office> rearrange(List<Office> source, String... locations) { 
    Map<String, List<Office>> map = new HashMap<>(); 
    for (Office office : source) { 
     List<Office> lst = map.get(office.getLocation()); 
     if (lst == null) { 
      lst = new ArrayList<>(); 
      map.put(office.getLocation(), lst); 
     } 
     lst.add(office); 
    } 
    List<Office> resultList = new ArrayList<>(); 
    for (String loc : locations) { 
     List<Office> partial = map.get(loc); 
     if (partial != null) { 
      resultList.addAll(partial); 
     } 
    } 
    return resultList; 
} 

上一頁變異與lambda表達式:

public static List<Office> rearrange2(List<Office> source, String... locations) { 
    Map<String, List<Office>> map = source.stream().collect(Collectors.toMap(
      Office::getLocation, 
      o -> {List<Office> lst = new ArrayList<>(); lst.add(o); return lst;}, 
      (offices, offices2) -> {offices.addAll(offices2); return offices;})); 
    return Arrays.asList(locations).stream() 
      .filter(map::containsKey) 
      .map(map::get) 
      .flatMap(Collection::stream) 
      .collect(Collectors.toList()); 
} 
+0

我在看你的第一個方法,但它顯然使用了Java 1.7和更低版本中不允許的lambda表達式。我使用1.7 – user1892775

+0

@ user1892775將lambda替換爲:new Comparator (){public int compare(Office o1,Office o2){return locs.indexOf(o1.getLocation()) - locs.indexOf(o2.getLocation(); \t }} – Rustam

相關問題