3 回答
TA贡献1820条经验 获得超2个赞
我认为你正在尝试做这样的事情:
Map<String,Double> alreadyMade = new HashMap<>();
for (Tips tips : new ArrayList<Tips>()) {
// If this time doesn't exist in the map then add it to the map with the
// value tips.getTips(). If this time does exist in the map then add
// the value of tips.getTips() to the value that is already in the map.
alreadyMade.merge(tips.getTime(), tips.getTips(), (Double a, Double b) -> a + b);
}
// go through each map entry. The keys are the times and the values are the tip totals for that time.
for (Map.Entry<String, Double> entry : alreadyMade.entrySet()) {
System.out.println("Time: " + entry.getKey() + " Tips: " + entry.getValue());
}
注意:我无法对此进行测试,因为我正在运行 Java 7,并且此地图功能在 Java 8 之前不可用。
TA贡献1794条经验 获得超7个赞
在 Java 8+ 中,您可以使用流 API 按时间分组:
Map<Date, Integer> alreadyMade = data.getTips().stream() .collect(groupingBy(Tip::getTime, summingInt(Tip::getTips)));
TA贡献1775条经验 获得超8个赞
我会这样做:
这是你的提示课(我认为)
public class Tip{
Date date;
float tip;
public Tip(Date date, float tip){
this.date = date;
this.tip = tip;
}
}
这就是(“算法”)
//To Format the Dates
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
//Input
ArrayList<Tip> tips = new ArrayList<Tip>();
//Just some Data for testing
tips.add(new Tip(ft.parse("11-04-2019"), 2.40F));
tips.add(new Tip(ft.parse("25-04-2019"), 3.30F));
tips.add(new Tip(ft.parse("25-04-2019"), 0.90F));
//Output
ArrayList<Date> dates = new ArrayList<Date>();
ArrayList<Float> sum = new ArrayList<Float>();
for(Tip tip : tips){ //Go through each Tip
int match = dates.indexOf(tip.date); //Look if the date is already in the array (if not -> -1)
if(match == -1){ //If not add it
dates.add(tip.date);
sum.add(tip.tip);
}else { //If yes set it
sum.set(match, sum.get(match) + tip.tip);
}
}
//Output to console
for(int i = 0; i < dates.size(); i++){
System.out.println(ft.format(dates.get(i)).toString() + " " + String.valueOf(sum.get(i)));
}
还有一个带有地图或配对的解决方案,但我从未使用过它们(不是专业编码器)。还要确保尝试捕获 ParseException。我希望这就是你的意思。:)
添加回答
举报