[英]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.