简体   繁体   中英

Issue with Sorting List using collections in java

I have a list with Order Entries. Each order entry has a base price. I want to sort this list on entry.basePrice descending (enty.basePrice == 0 entries should be at the bottom).

In this list, either no entry will have 0 price or one entry will have. I am doing like this ..

final Collection<AbstractOrderEntryModel> orderEntry = Collections2.filter(source.getEntries(),
            new Predicate<AbstractOrderEntryModel>()
            {
                @Override
                public boolean apply(final AbstractOrderEntryModel arg)
                {
                    return arg.getBasePrice().doubleValue() == 0 ? true : false;
                }
            });

Here I m filtering my entry which having baseprice = 0.0 Now How I will remove and add this item (orderEntry.iterator().next()) at last in OrderEntry List?

If its not a recommended solution, and it can be possible through Collections.sort also then please give me solution.

As far as I understand, you want to put an item matching a predicate at the end of the list. This can be done straightforward:

List<AbstractOrderEntryModel> list=source.getEntries()
final Collection<AbstractOrderEntryModel> orderEntry = Collections2.filter(list,
  new Predicate<AbstractOrderEntryModel>()
  {
    public boolean apply(final AbstractOrderEntryModel arg)
    {
        return arg.getBasePrice().doubleValue() == 0;
    }
  });
if(!orderEntry.isEmpty()) {
  assert orderEntry.size()==1; // so you said in your question
  AbstractOrderEntryModel e=orderEntry.iterator().next();
  list.remove(e);
  list.add(e);
}

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