有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何验证列表中的元素是否按字母顺序排序

I am using the following code to get the text values for employees from a web table and holding it in a list.Now i need to verify the employees stored in the list are in alphabetical order or not.

  int count = a.getobjectcount(//*[@id='GridTable']/tbody/tr[*]);
    List< String> list = new List<String>();
    for(int i=0;i<=count-1;i++){
    a.getTextFromElement("//*[@id='emp_" +i+ "']");

    //Using for loop to get the number of employees and store it in a list

 list.add(element)// i am adding employees to the list here   
  }

在这里,我需要验证员工是否按字母顺序排列,或者布尔==true;如果员工按字母顺序排列


共 (3) 个答案

  1. # 1 楼答案

    调用此方法:

    public static <E extends Comparable<E>> boolean isSorted(Iterable<E> coll) {
        E prev = null;
        for (E value : coll) {
            if (prev != null && prev.compareTo(value) > 0)
                return false;
            prev = value;
        }
        return true;
    }
    
  2. # 2 楼答案

    知道您正在使用列表数据结构,就可以从Collections API调用sort方法

    // Sorts the list of employees
    Collections.sort(list);
    
  3. # 3 楼答案

    下面的代码用于排序验证

    public Boolean validateSorting(){
    int count = a.getobjectcount(//*[@id='GridTable']/tbody/tr[*]);
        List< String> list = new List<String>();
        for(int i=0;i<=count-1;i++){
        a.getTextFromElement("//*[@id='emp_" +i+ "']");
    
        //Using for loop to get the number of employees and store it in a list
    
     list.add(element)// i am adding employees to the list here   
      }
     var y = list.First();
                return list.Skip(1).All(x =>
        {
           Boolean b = y.CompareTo(x) < 0;
            y = x;
            return b;
        });
    }