简体   繁体   中英

OrderByDecending(LINQ) equivalent in Java

Hi I am ac# developer getting into Java. The question is simple:

How can i write the below c# code into Java and still get it to work:

myCoffeeList.OrderByDescending(x => x.Name?.ToLower()?.Trim() == sender.Text.ToLower()?.Trim()));

My sender.Text is basically a textbox.Text with a value like Cappuccino .

What does the above code do?

Well I have a collection of coffee and I want that the name of the coffee that exactly matches the sender.text should be on top and the rest can be of the order returned from the server.

I've checked out the below:

  1. list.streams to use something like a LINQ

  2. Anotation type OrderBy but it's related to databases

List<Coffee> sorted = lst.stream()
                .sorted(Comparator.comparing(s -> !s.trim().equalsIgnoreCase(sender.trim())))
                .collect(Collectors.toList());

Use Comparable and the sort method:

List<String> coffee = new ArrayList<>();
coffee.add("C");
coffee.add("A");
coffee.add("B");
coffee.add("D");

String top = "D";
coffee.sort((a, b) -> a.equals(top) ? -1 : 0);
coffee.forEach(System.out::println);

EDIT: for natural order use:

coffee.sort((a, b) -> a.equals(top) ? -1 : a.compareTo(b));

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