有 Java 编程相关的问题?

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

java ArrayList字符串到int排序顺序

我需要验证“升序排序顺序”选项卡是否正常工作。 但当我比较结果时,由于一位数和两位数的原因,它不起作用。 如何将ArrayList转换为int?这样行吗

        ArrayList<String> obtainedList = new ArrayList<>();
    List<WebElement> elementList = driver.findElements(By.xpath("//mat-table//mat-row/mat-cell[2]"));
    for (WebElement we : elementList) {
        obtainedList.add(we.getText());
    }
    // This is where I should convert array to int ?

    ArrayList<String> sortedList = new ArrayList<>();
    for (String s : obtainedList) {
        sortedList.add(s);
    }

    Collections.reverse(sortedList);
    Collections.sort(sortedList);

    Reporter.log(AddRule + obtainedList + sortedList + " Cloumn is display in  Ascending order");
    Add_Log.info(AddRule + obtainedList + sortedList + " Cloumn is display in  Ascending order");
    List<String> labels = elementList.stream().map(WebElement::getText).collect(Collectors.toList());
    SortedSet<String> sorted = new TreeSet<>(labels);
    assertThat(labels, contains(sorted));

    Assert.assertTrue(sortedList.equals(obtainedList));

输出

编号[5,7,8,10,11,12,19,22,92,96,98,99][10,11,12,19,22,5,7,8,92,96,98,99]列按升序显示

由于一位数和两位数的数字,排序不起作用。 如果我把字符串数组转换成int,那行吗?如何修复此代码


共 (2) 个答案

  1. # 1 楼答案

    当然,如果您将obtainedList转换为List<Integer>,它将起作用

    List<Integer> obtainedList = new ArrayList<>();
    
    for(int i = 0; i < 10; i ++) {
        obtainedList.add(RandomUtils.nextInt(100));
    }
    
    Collections.reverse(obtainedList);
    Collections.sort(obtainedList);
    
    System.out.print(obtainedList);
    

    enter image description here

  2. # 2 楼答案

    您可以通过stream#mapstream#sortedList<String>投影到List<Integer>对元素进行排序,然后最终收集到列表中

    List<Integer> result = obtainedList.stream()
                                       .map(Integer::valueOf)
                                       .sorted() // sort the elements
                                       .collect(Collectors.toList());
    

    或典型的for循环:

    List<Integer> sortedList = new ArrayList<>();
    for (String s : obtainedList) 
            sortedList.add(Integer.valueOf(s));
    Collections.sort(sortedList); //sort the list after accumulating all the elements