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
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 (int i : list){
if (i >max)
max=i;
}
System.out.println(max) //print the maximum value of the array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.