[英]How to get highest value from ArrayList and display the info
我需要從ArrayList中找到最高的價值(銷售額),並顯示每個季度哪個商店的銷售額最高。
BufferedReader inputFile = null;
PrintWriter outputFile = null;
BookStore bs;
ArrayList <BookStore> data = new ArrayList();
try
{
inputFile = new BufferedReader (new FileReader ("bookstoresales.txt"));
outputFile = new PrintWriter (new FileWriter ("bookstoreoutput.txt"));
String indata = null;
while ((indata = inputFile.readLine()) != null)
{
System.out.println (indata);
StringTokenizer st = new StringTokenizer (indata, ",");
String storeBranch = st.nextToken();
String storeAddress = st.nextToken();
double jan = Double.parseDouble (st.nextToken());
double feb = Double.parseDouble (st.nextToken());
double mac = Double.parseDouble (st.nextToken());
double apr = Double.parseDouble (st.nextToken());
double may = Double.parseDouble (st.nextToken());
double jun = Double.parseDouble (st.nextToken());
double jul = Double.parseDouble (st.nextToken());
double aug = Double.parseDouble (st.nextToken());
double sep = Double.parseDouble (st.nextToken());
double oct = Double.parseDouble (st.nextToken());
double nov = Double.parseDouble (st.nextToken());
double dec = Double.parseDouble (st.nextToken());
bs = new BookStore (storeBranch, storeAddress, jan, feb, mac, apr, may, jun, jul, aug, sep, oct, nov, dec);
data.add(bs);
}
outputFile.println ("\n\n=================================== The Highest Bookstore Sales Per Quarter ===================================");
for (int i=0; i<data.size(); i++)
{
//This is where I got stucked.
}
outputFile.println ("\nQuarter 1 : The Highest sales is Bookstores : " + //getbranch name from the highest sales + " with value of + //the highest value");
inputFile.close();
outputFile.close();
}
catch (FileNotFoundException fnf)
{
System.out.println ("File not found!");
}
catch (IOException ioe)
{
System.out.println (ioe.getMessage());
}
}
}
現在,我需要獲取並顯示店鋪名稱以及最高的銷售價值。 對於ArrayList,我感到很困惑。
創建一個名為max
的變量。 在循環中,如果列表中的項目高於max
,則將max
設置為該項目。
BookStore max = data.get(0);
for (BookStore bs : data) {
if (bs.sales > max.sales) {
max = bs;
}
}
使用Java 8:
BookStore max =
data.stream()
.max(Comparator.comparingDouble(bs -> bs.getJan() + ... + bs.getDec()))
.get();
另一種方法是使用Collections.max() :
Collections.max(data, new Comparator<BookStore>() {
@Override
public int compare(BookStore a, BookSore b) {
return a.sales - b.sales;
}
});
或者,如果BookStore
是Comparable
,則只需:
Collections.max(data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.