简体   繁体   中英

Java : sort array

I have list of objects.
Object = Invoice_id,client_name

My list looks like that :

1,tom
1,tom
1,tom
2,tim
2,tim
3,rob
3,rob
4,mike
4,mike

I would like to obain that :

1,tom
2,tim
3,rob
4,mike

I have tried that :

for (Invoice invoice : invoices){
  mapOfInvoicesId.put(invoice.getId(), invoice.getId());
}
mapOfInvoicesId.keySet()

But the ids are not in the same order as in the initial list. I don't know why. I want to keep the same order.

If anyone knows why...

Thanks

  1. Implement equals and hashCode in your data object class.
  2. Use LinkedHashSet (to keep order as you add items) to keep only distinct ones.
  3. Add all items to the set.
  4. Iterate over the set and print all items.

Profit!

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