1

I am fetching response in sorted order from Get call using "http am.com/au/v/so?sort=name". It fetches the results in sorted order. How can I assert the the name in the list is in alphabetical order.

List<String> list = new ArrayList<String>();
        for (Aml aml : value.getResults()) {
            name = aml.getName());
selvi
  • 1,271
  • 2
  • 21
  • 41

2 Answers2

3

A naive but working solution:

List<String> received = insert_code_for_get_call_here();
List<String> sorted = received.stream().sorted().collect(Collectors.toList());
assertEquals(sorted, received);

What does this do? It takes the received values, sorts them again, and then checks if the resulting list is equal to the original list. If the original list was already sorted, this is should be true. If the received list was not sorted, they will differ.

Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26
  • Maybe can try``import static org.junit.Assert.assertArrayEquals;``. Since ``assertArrayEquals()`` will compare the order as well. – R.yan Apr 16 '18 at 07:48
  • He's not using JUnit, not to mention we're dealing with lists, not arrays – Jeroen Steenbeeke Apr 16 '18 at 07:49
  • 1
    This solution has one problem - it sorts capital characters and small characters separately. For example, "Adam Clare, bob" will be sortes as "bob, Adam, Clare". Add `String.CASE_INSENSITIVE_ORDER` as a parameter of sorted() to avoid this problem. – Petersaber Sep 15 '21 at 12:33
2

You can use something like this

String prev = "";
for(Ami ami : value.getResults())
{
  String currentName = ami.getName();
  if(prev.compareTo(currentName) > 0)
  { 
     return false;
  }
  prev = currentName;
}
return true;