A list is sorted in ascending order if it is empty or each item except the last one is less than or equal to its successor. Define a predicate isSorted that expects a list as an argument and returns True if the list is sorted, or returns False otherwise. (Hint: For a list of length 2 or greater, loop through the list and compare pairs of items, from left to right, and return False if the first item in a pair is greater.)

Respuesta :

tanoli

Answer:

Predicates are function which takes one argument and after performing some checks it returns boolean value.

Explanation:

Java Code

import java.util.*;

import java.util.function.Predicate;

public class OrderList{

  public static void main(String []args) {

      Predicate<List<Integer>> predicate = (list)->{

          if(list.size()<=1){

              return true;

          }

          for(int i=0;i < list.size()-1; i++){

              if(list.get(i)>list.get(i+1)){

                  return false;

              }

          }

          return true;

      };

       List<Integer> list = Arrays.asList(1,3,4,5,6,7,8);

       System.out.println("Is List Sorted : "+predicate.test(list));

  }

}

Code Explanation

First of all define predicate, which takes list of integers as input.

First check whether list has 0 or 1 elements init, if yes then return true as one or zero element list is already sorted.

If elements in a list are greater then 1 then we started a for loop from 0 to list size minus one. As we are checking next index number in current index iteration.

If left pair item value is greater then its successor then if conditions execute and return false as the elements are not in sorted order.

Output

The above code output is

Is List Sorted :true

ACCESS MORE