how to convert forEach to lambda

前端 未结 3 384
旧时难觅i
旧时难觅i 2021-01-15 09:02
Iterator rateIt = rates.iterator();
int lastRateOBP = 0;
while (rateIt.hasNext())
{
    Rate rate = rateIt.next();
    int currentOBP = rate.getPersonCou         


        
3条回答
  •  有刺的猬
    2021-01-15 09:57

    The simplest solution is

    Set seen = new HashSet<>();
    rates.removeIf(rate -> !seen.add(rate.getPersonCount()));
    

    it utilizes the fact that Set.add will return false if the value is already in the Set, i.e. has been already encountered. Since these are the elements you want to remove, all you have to do is negating it.

    If keeping an arbitrary Rate instance for each group with the same person count is sufficient, there is no sorting needed for this solution.

    Like with your original Iterator-based solution, it relies on the mutability of your original Collection.

提交回复
热议问题