代码之家  ›  专栏  ›  技术社区  ›  Azeem Haider

Java 8中的排序列表和应用限制

  •  -1
  • Azeem Haider  · 技术社区  · 8 年前

    我正在使用 List 在里面 java8 .

    我有一个自定义类对象的列表。我需要根据对象属性以排序形式用对象填充此列表,排序后我需要在列表中应用限制。

    例如

      public class TempClass {
           String name; int count;
           //... Getter, setter and constructor
      }
    
      // Suppose I have a list with TempClass
      List<TempClass> tempList = new ArrayList<>();
    
      // There are five obj Of TempClass
      TempClass obj1, obj2, obj3, obj4, obj5;
    
      // I need to insert these object according to "count" property
      // Suppose obj1.getCount = 10, obj2 = 7, obj3 = 11, obj4 = 8, obj5=12
      /* I need to add element in order
          0 - obj5
          1 - obj1
          2 - obj3
          3 - obj4
          4 - obj2
      */
    

    第二件事我需要申请限制 列表 排序后。我只需要从顶部开始的3个元素就可以了 obj5, obj1, obj3

    你能告诉我怎么做吗?我在谷歌云上使用java8 端点

    2 回复  |  直到 8 年前
        1
  •  0
  •   neuo    8 年前
    PriorityQueue<TempClass> queue = new PriorityQueue<>(Comparator.comparingInt(TempClass::getCount));
    for (TempClass temp : tempList) {
        queue.offer(temp);
        if (queue.size() > 3) {
            queue.poll();
        }
    }
    
    LinkedList<TempClass> result = new LinkedList<>();
    while (queue.size() > 0) {
        result.push(queue.poll()); //obj5, obj1, obj3
    }
    
        2
  •  0
  •   Azeem Haider    8 年前

    我找到了答案。

    对于 List 排序使用lambda表达式或类似表达式。

    这样地。

    tempList.sort(Comparator.comparingInt(t -> t.getCount()));
    

    和限制。

    tempList= tempList.stream().limit(3).collect(Collectors.toList());