使用 foreach 将 arrayList 与自身进行比较,并且不包含重复项



我正在使用foreach将arrayList与自身进行比较。 我有一个数组列表,其中包含服务员的小费,每个对象都有一个日期"dd-MM-yyy"和一个金额(双倍), 现在我想添加同一天的所有交易,所以我得到了当天的总数,可以在服务员之间分配。 没有重复。 我看遍了这里,但我似乎找不到解决方案。 我真的希望你们能帮忙,我知道这有点尴尬,因为问题很简单,但我已经为此工作了几天,但我被卡住了。

我有一个更长的算法,但它不起作用,我在网上找不到任何解决方案,所以我把它全部分解为最基本的组件,并检查了每个步骤,很早就出现了这个问题: 我正在使用本地 arrayList 来确保我不会一遍又一遍地将相同的日子相互比较。 if(!alreadyMade.contains(tips1.getTime()) 后跟 alreadyMade.add(tips1.getTime()) 似乎正在产生重复项,这在我看来毫无意义。 我想要的只是从同一个 arrayList 中添加同一天的所有事务。

public void dist(){

double day = 0;
List<String> alreadyMade = new ArrayList<>();
for (Tips tips : data.getTips()) {
for (Tips tips1 : data.getTips()) {
if(tips.getTime().equals(tips1.getTime())) {
if (!alreadyMade.contains(tips1.getTime())){
alreadyMade.add(tips1.getTime());
day += tips.getTips();
}
}
}
System.out.println(day);
day = 0;
}
}

我希望打印一天,但它打印了很多没有意义的数字

我认为您正在尝试做这样的事情:

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 之前不可用。

在 Java 8+ 中,您可以使用流 API 按时间分组:

Map<Date, Integer> alreadyMade = data.getTips().stream()
  .collect(groupingBy(Tip::getTime, summingInt(Tip::getTips)));

我会像下面这样做:

这是你的提示课(我认为)

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。我希望这就是你的意思。:)

最新更新