【问题标题】:ArrayList String to int sorting orderArrayList String 到 int 排序顺序
【发布时间】:2019-01-10 02:21:49
【问题描述】:

我需要验证升序排序选项卡是否正常工作。 但是当我比较结果时,由于一位数和两位数,它不起作用。 如何将 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 会起作用吗?如何修复此代码?

【问题讨论】:

  • 你已经有了解决方案,为什么不试试呢?我没有办法,但我想说你应该先尝试自己解决,这不是一个困难的问题,我认为你可以处理它。
  • @AlexDing 我试过了,但无法解决请在下面的评论仍然无效后提供帮助

标签: java selenium sorting arraylist int


【解决方案1】:

您可以从List&lt;String&gt; 投影到List&lt;Integer&gt; 通过stream#map 然后stream#sorted 对元素进行排序,然后最终收集到一个列表。

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 

【讨论】:

  • 这项工作但我的断言失败 java.lang.AssertionError: Lists different at element [0]: 5 != 5 expected [5] but found [5] 我该如何解决这个问题?
【解决方案2】:

当然,如果您将obtainedList 转换为List&lt;Integer&gt;,它将起作用。

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);

【讨论】:

  • 我收到错误“RandomUtils 类型中的方法 nextInt() 不适用于参数 (int)”我该如何解决这个问题?
猜你喜欢
  • 1970-01-01
  • 2013-09-09
  • 2019-02-03
  • 1970-01-01
  • 2019-02-20
  • 2020-04-06
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多