简体   繁体   中英

Sort List and apply limit in Java 8

I'm using List in java8 .

I have a list with custom class object. I need to fill this list with object in sorted form according to object property and after sorting I need to apply limit in list.

For example

  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
  */

Second thing I need to apply limit in List after sorting. I need only 3 elements from Top in this case only obj5, obj1, obj3

Can you please let me know how can I do that ? I'm using java8 with Google cloud endpoints

I found answer.

For List sort use lambda expression or Comparable.

Like this.

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

And for limit.

tempList= tempList.stream().limit(3).collect(Collectors.toList());
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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM