2 回答
TA贡献1875条经验 获得超3个赞
首先,我认为创建一个简单的类来保存数据是有意义的,因为使用对象而不是值数组来过滤和排序会更容易。
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);
});
TA贡献2065条经验 获得超13个赞
我会将文件的全部内容加载到内存中并将其存储在java.util.List<String>
. List
然后你可以按Name和admin排序。然后只需遍历List
. 每当您点击不同的Name时,您就知道其关联的admin值是最大的。因此,您将其添加到您的 first 中ArrayList
,并将所有其他人添加到您的 secondArrayList
中。
添加回答
举报