简体   繁体   English

如何从 ArrayList 中获取最大值

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

I'm trying to get highest price of a product.我试图获得产品的最高价格。 I'm able to store the prices in an object.我能够将价格存储在一个对象中。 I want to know how to get the maximum value from that object.我想知道如何从该对象中获取最大值。 Below is my code!下面是我的代码!

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

    }

Output i have..我有输出..

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

Map the strings to ints (or longs, or some type of currency), then you can get the max using a Comparator将字符串映射到整数(或长整数,或某种类型的货币),然后您可以使用比较器获得最大值

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

You first need to convert the numbers to int, and than you can use Collections.max on the list您首先需要将数字转换为 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

create an int and call it max (=0), run on each element of the list using a loop (for loop recommended), on each element, check if its bigger than max, if yes, put the value in max, here is a little code, in case the list is called "list", change it to whatever you want创建一个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