import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class Partition extends HashMap { public Partition() { super(); } public Partition(Partition p) { super(p); } public Partition(int... terms) { this(); for(int term : terms) addTerm(term); } public void addTerm(int term) { merge(term, 1, Integer::sum); } public boolean removeTerm(int term) { if(!containsKey(term)) return false; compute(term, (k, v) -> v == 1 ? null : v - 1); return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Partition that = (Partition) o; return super.equals(that); } @Override public String toString() { return keySet().stream().sorted() .flatMap(k -> Stream.generate(() -> k).limit(get(k))) .mapToInt(Integer::intValue) .mapToObj(Integer::toString) .collect(Collectors.joining("+")); } }