![](/img/trans.png)
[英]java reading from csv file and storing its information into ArrayList<class>
[英]Getting the highest column value from csv file and storing it into arraylist
我正在嘗試將具有最高管理值的Name的Sub Name存儲到arraylistONE中。
在這種情況下,
1 3/4 cups all-purpose flour
1/4 teaspoon baking soda and 1/2 cup of plain
8 teaspoons of baking powder
如果名稱僅具有0個管理值,則應為,
1 cup brewed coffee
對於具有較小管理員值的其余數據,它們將存儲到arraylistTWO中。
我被困在讀取csv文件中,我不知道如何將具有最高管理員值的名稱的子名稱存儲到arraylistONE中,而對於具有較低管理員值的其余數據,我不知道如何存儲到arraylistTWO中。
這是我到目前為止完成的工作:
try {
br = new BufferedReader (new FileReader ("/sdcard/TABLE_BF.csv"));
while ((sCurrentline = br.readLine ()) != null) {
subIng.add(sCurrentline.split (","));
}
arrSubIng = new String[subIng.size ()][];
subIng.toArray (arrSubIng);
} catch (IOException e) {
e.printStackTrace ();
}
首先,我認為創建一個簡單的類來保存數據是有意義的,因為使用對象而不是值數組進行過濾和排序將更加容易。
public class Ingredient {
String name;
String subName;
int status;
int admin;
public Ingredient(String name, String subName, String status, String admin) {
this.name = name;
this.subName = subName;
this.status = Integer.valueOf(status);
this.admin = Integer.valueOf(admin);
}
public String getName() {
return name;
}
public int getAdmin() {
return admin;
}
//more get and set methods here. I have only included what is needed for my answer
}
然后,您將閱讀並創建一個Ingredient
對象列表。
List<Ingredient> data = new ArrayList<>();
try {
String sCurrentline = null;
BufferedReader br = new BufferedReader(new FileReader("/sdcard/MAIN_BF.csv"));
while ((sCurrentline = br.readLine()) != null) {
String[] arr = sCurrentline.split(",");
Ingredient ingredient = new Ingredient(arr[0], arr[1], arr[2], arr[3]);
data.add(ingredient);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
然后我們按名稱將列表分組到Map
Map<String, List<Ingredient>> ingredientsByName = data.stream().collect(Collectors.groupingBy(Ingredient::getName));
並在該地圖上循環查找每種成分的最大管理價值,並將其添加到正確的列表中
List<Ingredient> main = new ArrayList<>();
List<Ingredient> other = new ArrayList<>();
//Sort on `admin` in descending order
Comparator<Ingredient> compartor = Comparator.comparing(Ingredient:: getAdmin, (i1, i2) -> {
if (i2 > i1) {
return -1;
} else if (i2 < i1) {
return 1;
}
return 0;
});
//Go through each list (ingredient) and find the one with max `admin` value
//and add it to the `main` list then add the rest to `other`
ingredientsByName.forEach( (k, group) -> {
Ingredient max = group.stream().max(compartor).get();
if (max.getAdmin() == 0) {
max = group.get(0);
}
main.add(max);
group.remove(max);
other.addAll(group);
});
我會將文件的全部內容加載到內存中,並將其存儲在java.util.List<String>
。 然后,您可以按名稱和admin對List
進行排序。 然后只需遍歷List
。 每當您點擊其他Name時 ,您就會知道其關聯的admin值是最大的。 因此,您將其添加到第一個ArrayList
並將所有其他添加到第二個ArrayList
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.