簡體   English   中英

如何從 ArrayList 中獲取最大值

[英]How to get the maximum value from an ArrayList

我試圖獲得產品的最高價格。 我能夠將價格存儲在一個對象中。 我想知道如何從該對象中獲取最大值。 下面是我的代碼!

public class amazon {
    static WebDriver driver;

    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver", "C://Selenium/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("xyzzz.com");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        amazon az = new amazon();
        az.run();

        }

    public void run() throws Exception {


            List<Object> obj = new ArrayList<Object>();

            List<WebElement> tag = driver.findElements(By.xpath("//span[@class='a-price-whole']"));

            int i;
            for(i=0; i<tag.size(); i++) {

                obj.add(tag.get(i).getText());

            }

            System.out.println(obj);
            driver.close();

    }

我有輸出..

[64,900, 99,900, 1,23,900, 64,900, 64,900, 69,900, 64,900, 64,900, 1,23,900, 52,900]

將字符串映射到整數(或長整數,或某種類型的貨幣),然后您可以使用比較器獲得最大值

int max = driver.findElements(By.xpath("//span[@class='a-price-whole']")).stream() 
    .map(WebElement::getText)
    .map(s -> s.replace(",", ""))
    .map(Integer::parseInt)
    .max(Integer::compare)
    .get();

您首先需要將數字轉換為 int,然后您可以在列表中使用Collections.max

List<Integer> prices = new ArrayList<>();
List<WebElement> tags = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
for (WebElement tag: tags) {
    prices.add(Integer.parseInt(tag.getText().replace(",", "")));
}
System.out.print(Collections.max(prices)); // 123900

創建一個int並將其命名為max(=0),使用循環(推薦for循環)在列表的每個元素上運行,在每個元素上,檢查它是否大於max,如果是,則將值放入max,這里是一些代碼,如果列表被稱為“列表”,請將其更改為您想要的任何內容

int max=0;
for (int i : list){
  if (i >max)
    max=i;
}
System.out.println(max) //print the maximum value of the array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM