2

I have an ArrayList of Customs Orders as below

ArrayList<Customs> customsList = new ArrayList<Customs>();

Example of my Customs class

public class Customs
{
    private String  userId;

    private String  customLabel;
    private Double  itemPrice;
    private Double  weight;

//getters and setters
}

The customsList can contain multiple Customs objects which can have the same uesrId which would indicate they are from the same customer.

I am trying to write a method which checks if there is more than one userId repeated in the ArrayList, and if it it repeated more than once it would add the itemPrice and weight of them together and then put it in another list as one.

What would be the best way to do this?

15
  • 1
    Rather than asking for a solution to your problem, please show us the solution you have tried and ask a specific question about why it isn't working as you'd like,
    – scottb
    Aug 2, 2015 at 3:08
  • @scottb: In this scenario it's not entirely necessary. It's like expecting someone to know everything about this problem - if they did, why would they ask?
    – Makoto
    Aug 2, 2015 at 3:10
  • 1
    @durron597: You're missing the other half - combining the elements together into one omni-element. The methods described in your linked duplicate aren't capable of expressing that.
    – Makoto
    Aug 2, 2015 at 3:13
  • 1
    @BenKnoble With Java 8 you can do it in one line too. Aug 2, 2015 at 3:19
  • 1
    @Makoto: the question strongly resembles a homework type of problem. The value of seeking an answer to such problems is greatly augmented by seeking the solution using the knowledge that one is supposed to already have. I am also circumspect about the OP's reticence to seek answers to existing questions.
    – scottb
    Aug 2, 2015 at 3:23

3 Answers 3

0

Hm, There is tricky way can do that with using distinct, overriding hashCode and equals. Need to care this way whenneed other sort for your class.

public class Test {
    public static void main(String[] args) {
        ArrayList<Customs> customsList = new ArrayList<Customs>();
        Customs c1 = new Customs(123L, "bad", 23d, 34d);
        Customs c2 = new Customs(122L, "bad", 23d, 34d);
        Customs c3 = new Customs(125L, "bad", 23d, 34d);
        Customs c4 = new Customs(122L, "bad", 23d, 34d);
        Customs c5 = new Customs(122L, "bad", 23d, 34d);
        Customs c6 = new Customs(123L, "bad", 23d, 34d);
        customsList.add(c1);
        customsList.add(c2);
        customsList.add(c3);
        customsList.add(c4);
        customsList.add(c5);
        customsList.add(c6);

        customsList.stream().distinct().collect(Collectors.toList()).forEach(t -> {
                    System.out.println(t.getUserId());
                    System.out.println(t.getItemPrice());
                    System.out.println(t.getWeight());
                }
        );
    }
}

class Customs {
    private long userId;

    private String customLabel;
    private Double itemPrice;
    private Double weight;

    public Customs(long userId, String customLabel, Double itemPrice, Double weight) {
        this.userId = userId;
        this.customLabel = customLabel;
        this.itemPrice = itemPrice;
        this.weight = weight;
    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getCustomLabel() {
        return customLabel;
    }

    public void setCustomLabel(String customLabel) {
        this.customLabel = customLabel;
    }

    public Double getItemPrice() {
        return itemPrice;
    }

    public void setItemPrice(Double itemPrice) {
        this.itemPrice = itemPrice;
    }

    public Double getWeight() {
        return weight;
    }

    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public boolean equals(Object o) { //Override equals method for distinct, at the same time add the weight and itemPrice, it's a tricky way. if you want to do that, you need to make sure, there will be no other sort need.
        if (!(o instanceof Customs)) {
            return false;
        }
        Customs c = (Customs) o;
        if (this.userId == c.userId) {
            c.itemPrice += this.itemPrice;
            c.weight += this.weight;
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() { //Override hashCode for distinct
        return Long.valueOf(this.userId).hashCode();
    }


//getters and setters
}
0

There's probably a Java 8 one-liner out there, but I prefer to shy away from those if I need to. Note that this solution is exclusively in Java 8.

Essentially, the process you need to follow:

  • Split up your elements into the appropriate buckets (by user ID)
  • Combine the elements together
  • Return a new list containing an individual element.

You don't specify which customLabel wins out overall, but here's an approach that merges it with the last one.

Add this method to Customs:

public void combine(Customs another) {
    this.userId = another.getUserId();
    this.customLabel = another.getCustomLabel();
    this.itemPrice = null == this.itemPrice ? another.getItemPrice() : this.itemPrice + another.getItemPrice();
    this.weight = null == this.weight ? another.getWeight() : this.weight + another.getWeight();
}

The following lines of code break down the above steps. I'm using a collector here to combine the elements together in the final phase. As I go along, I'm basically adding the elements into another list for final parsing.

final Map<String, List<Customs>> groupedCustomsElements = customsList.stream()
                                                                     .collect(Collectors.groupingBy(Customs::getUserId));
final List<Customs> combinedResult = new ArrayList<>();
for (String s : groupedCustomsElements.keySet()) {
    combinedResult.add(groupedCustomsElements.get(s)
                                             .stream()
                                             .collect(Customs::new, Customs::combine, Customs::combine));
}

A cleaner solution may be to create your own custom list which extends ArrayList and augment the add method to suit your needs.

class CustomCombiningList extends ArrayList<Customs> {

    @Override
    public boolean add(Customs e) {
        int idx = indexOf(e);
        if(idx != -1) {
            add(idx, get(idx).combineAndReturn(e));
            remove(idx + 1); // clean up unneeded object; worth a unit test
        } else {
            super.add(e);
        }
        return true;
    }
}

This would require two new methods - combineAndReturn which actually returns the result of combine, and a definition of equals() for your Customs element. It may be a sight prettier to read than the convoluted lambda, too.

1
  • @pbabcdefp: Thanks for the tip on super - somehow I had missed that when typing incredibly fast. As for the extension of the list - that should be okay; if one doesn't want to go about it the invasive and seriously convoluted approach, than this is an alternative to that.
    – Makoto
    Aug 2, 2015 at 4:18
0

I will not repeat Makoto's answer about how to do it in Java8. Here is how to do it in Java 6:

    Map<String, Customs> groupedCustoms = new LinkedHashMap<String, Customs>();

    for (Customs custom : customs) {
        Customs aggrCustom = groupedCustoms.get(custom.getUserId());
        if (aggrCustom == null) {
            // create new aggregated record
            aggrCustom = new Customs(custom);
            groupedCustoms.put(custom.getUserId(), aggrCustom);
        } else {
            aggrCustom.aggregateWith(custom);
        }
    }

    List<Custom> results = new ArrayList<Customs>(groupedCustoms.values());

I assume that initial initial Customs are stored in List<Customs> customs. Also I assume that there is copy constructor in Customs that takes another Customs as argument and copies it's fields (analogue of clone) and aggregateWith method that takes another Customs as argument and adds it's metric fields to the current one.

Using LinkedHashMap to group records is required in order to make grouping "stable", i.e. preserve the original order of records.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.