2015-06-09 59 views
3

排序给出一个Java类的东西java8流分组和总金额

class Something { 
    private int parentKey; 
    private String parentName; 
    private int childKey; 
    private int noThings; 

    public Something(int parentKey, String parentName, int childKey, 
    int noThings) { 
    this.parentKey = parentKey; 
    this.parentName = parentName; 
    this.childKey = childKey; 
    this.noThings = noThings; 
    } 

    public int getParentKey() { 
    return this.parentKey; 
    } 

    public int getNoThings() { 
    return this.noThings; 
    } 
} 

我有一些对象的列表

List<Something> somethings = newArrayList(
      new Something(425, "Lemon", 44, 23), 
      new Something(123, "Orange", 125, 66), 
      new Something(425, "Lemon", 11, 62), 
      new Something(123, "Orange", 126, 32), 
      new Something(323, "Lime", 25, 101), 
      new Something(123, "Orange", 124, 88) 
); 

我希望能够对它们进行排序,以使他们按每个父对象的noThings和noThings的累积和排序。

所以,我结束了

List<Something> sortedSomethings = newArrayList(
      new Something(123, "Orange", 124, 88), 
      new Something(123, "Orange", 125, 66), 
      new Something(123, "Orange", 126, 32), 
      new Something(323, "Lime", 25, 101), 
      new Something(425, "Lemon", 11, 62), 
      new Something(425, "Lemon", 44, 23) 
); 

我知道,通过parentKey映射它和空话的总和

Map<Integer, Integer> totalNoThings = colns 
      .stream() 
      .collect(
        Collectors.groupingBy(
          Something::getParentKey, 
      Collectors.summingInt(ClientCollectionsReceived::getNoThings))); 

我想,也许包裹我的东西类,并具有总每父母键可能在某种程度上起作用。

class SomethingWrapper { 
    private int totalNoThingsPerClient; 
    private Something something; 
} 

但它看起来很多工作,而不是很优雅。

任何意见/想法将不胜感激。

List<Something> sorted=somethings.stream().sorted(
    Comparator.comparing((Something x)->totalNoThings.get(x.getParentKey())) 
      .thenComparing(Something::getNoThings).reversed()) 
    .collect(Collectors.toList()); 

回答

2

好,我们已经通过收集汇总信息

Map<Integer, Integer> totalNoThings = somethings.stream() 
    .collect(Collectors.groupingBy(Something::getParentKey, 
     Collectors.summingInt(Something::getNoThings))); 

那么所有你需要的是利用排序操作这些信息做所做的主要工作一个小的调整,而不是totalNoThings.get,它是totalNothings.indexOf

因此最终soln。是

List<Integer> totalNoThings 
    = somethings.stream() 
    .collect(Collectors.groupingBy(Something::getParentKey, 
        Collectors.summingInt(Something::getNoThings))) 
    .entrySet().stream() 
    .sorted(Map.Entry.comparingByValue()) 
    .map(Map.Entry::getKey) 
    .collect(Collectors.toList()); 


List<Something> sorted 
    = somethings.stream().sorted(
      Comparator.comparing(
      (Something obj)->totalNoThings.indexOf(
      obj.getParentKey())) 
    .thenComparing(Something::getNoThings).reversed()) 
      .collect(Collectors.toList()); 
+0

谢谢!我正准备在一段代码摔角后发布答案!我的解决方案不如您的解决方案,但遵循相同的逻辑。 – IncompleteCoder