Skip to content

Instantly share code, notes, and snippets.

@eoconnell
Created August 21, 2014 03:21
Show Gist options
  • Save eoconnell/b71465609418d5737f5a to your computer and use it in GitHub Desktop.
Save eoconnell/b71465609418d5737f5a to your computer and use it in GitHub Desktop.
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Compressor {
private Compressor() {};
public static <V extends ICompressible<K, V>, K> Collection<V> compress(Collection<V> original) {
Map<K, V> map = new HashMap<K, V>(original.size());
for (V o : original) {
if (map.containsKey(o.compressKey())) {
V n = map.get(o.compressKey());
V c = n.compress(o);
map.put(o.compressKey(), c);
} else {
map.put(o.compressKey(), o);
}
}
return map.values();
}
}
public interface ICompressible<K, V> {
K compressKey();
V compress(V o);
}
import java.util.ArrayList;
import java.util.Collection;
public class Item implements ICompressible<String, Item> {
private String id;
private int quantity;
public Item(String id, int quantity) {
this.id = id;
this.quantity = quantity;
}
@Override
public String compressKey() {
return id;
}
@Override
public Item compress(Item o) {
return new Item(id, o.quantity + quantity);
}
public static void main(String[] args) {
Item i1 = new Item("Square", 5);
Item i2 = new Item("Triangle", 10);
Item i3 = new Item("Square", 3);
Collection<Item> items = new ArrayList<Item>();
items.add(i1);
items.add(i2);
items.add(i3);
Collection<Item> compressedItems = Compressor.compress(items);
System.out.println(items);
// => [Square:5, Triangle:10, Square:3]
System.out.println(compressedItems);
// => [Square:8, Triangle:10]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment