1
String obtained = transactions.stream()
    .map(Transaction::getTrader)
    .map(Trader::getName)
    .sorted(String::compareTo)
    .collect(Collectors.joining(","));

What should I do if I want to reverse the natural alphabetical ordering in the returned string without writing a specific Comparator<String>, so that the concatenated string result starts with the names 'z..', 'y..', 'x..' and so on?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38

2 Answers2

2

In java, something like this can do the trick :

String obtained = transactions.stream()
                  .map(Transaction::getTrader).map(Trader::getName)
                  .sorted(Comparator.reverseOrder())
                  .collect(Collectors.joining(","));

Note that it works because String implements Comparable Interface.

colin aygalinc
  • 457
  • 4
  • 13
2

Only one operation is required to sort collection in reversed order.

String implements Comparable interface. The javadoc for java.lang.Comparable#compareTo() says that it returns:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object

To reverse order of collection you can:

  1. [recommended] use Comparator.reverseOrder (javadoc) which

    Returns a comparator that imposes the reverse ordering of the specified comparator. (...)

    List<String> strings = Arrays.asList("a","b","d", "c", "e");
    reversedOrderedStrings = strings.stream()
                                .sorted(Comparator.reverseOrder())
                                .collect(Collectors.joining(","));
    
  2. invert order of compared parameters

    reversedOrderedStrings = strings.stream()
                                .sorted((s1, s2) ->  s2.compareTo(s1))
                                .collect(Collectors.joining(","));
    
  3. [not recommended] change the sign of compareTo() method. This is not recommended as it can cause numeric overflow for Integer.MIN_VALUE

    reversedOrderedStrings = strings.stream()
                                .sorted((s1, s2) -> -s1.compareTo(s2))
                                .collect(Collectors.joining(","));
    

Output for all is the same:

System.out.println(reversedOrderedStrings);
e,d,c,b,a
gr7
  • 84
  • 8
  • 1
    You are right but the question says to not write your own comparator. I acknowledge that your method is faster and must be used. – colin aygalinc Nov 25 '16 at 16:14
  • Yes, i know i can do that, i was looking Collection.reverseOrder() method. –  Nov 25 '16 at 16:47
  • I should have used "sorted(Comparator.reverseOrder())" in my answer as described in [Reverse a comparator in Java 8](http://stackoverflow.com/questions/32995559/reverse-a-comparator-in-java-8). – gr7 Nov 25 '16 at 17:12
  • @Holger - corrected the answer. Thanks for remarks. – gr7 Nov 28 '16 at 15:00