0

I have this list of Entities:

@Entity
@Table(name = "filters")
public class Filters {

    private String filter_settings;

    private Integer position;
}

List:

List<RiskFilters> filter_list

I have simple numbers for 'position' - 1,2,3 and etc.

How I can sort the list of 'Filters' based on the 'position' number?

I tried this:

    List<RiskFilters> sorted_filter_list = Collections.sort(filter_list, Comparator.comparingInt(RiskFilters::getPosition));

But I get Type mismatch: cannot convert from void to List

Is there some way to fix this?

tkruse
  • 10,222
  • 7
  • 53
  • 80
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • Did you instantiate `filter_list`? – ngood97 Aug 10 '19 at 21:52
  • 4
    `Collections.sort()` does not return a value. It actually mutates (sorts) the List passed to it. Just run that method to sort it. – KellyM Aug 10 '19 at 21:53
  • Can you propose some solution, please? – Peter Penzov Aug 10 '19 at 21:54
  • @PeterPenzov Just write ` Collections.sort(filter_list, Comparator.comparingInt(RiskFilters::getPosition));` to sort the List. As long as it has been instantiated, the List will now be sorted. – KellyM Aug 10 '19 at 21:55
  • @KellyM ok, but I need to create a new sorted list from the old one. – Peter Penzov Aug 10 '19 at 21:58
  • @PeterPenzov Collections.sort will sort whatever is passed to it. If you need two separate lists, just create a new list from the old (`List sorted_filter_list = new ArrayList(filtered_list)`) and then sort the "new" list `Collections.sort(sorted_filter_list, Comparator.comparingInt(RiskFilters::getPosition))` – KellyM Aug 10 '19 at 22:05
  • @PeterPenzov so just `Collections.copy()` the `List` and `Collections.sort()` the copy. – Christian H. Kuhn Aug 10 '19 at 22:55
  • There are already many questions on sorting in Java at stackoverflow. For the interactive help experience, try the chat. – tkruse Aug 11 '19 at 00:20

1 Answers1

2

Thats because Collections.sort(list) sorts the list you send them. You don't need to assign it back into you're list like you would with String.

List<RiskFilters> filter_list
Collections.sort(filter_list, Comparator.comparingInt(RiskFilters::getPosition));
nishantc1527
  • 376
  • 1
  • 12