75 lines
2.2 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/dynatrash/DynaTrash.java
2020-10-07 13:35:40 -06:00
// (c)2020 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-11-03 12:00:44 -08:00
// Using a Map of Lists and RTTI to automatically
// sort trash into Lists. This solution, despite
// the use of RTTI, is extensible.
2016-07-28 12:48:23 -06:00
// {java patterns.dynatrash.DynaTrash}
2015-06-15 17:47:35 -07:00
package patterns.dynatrash;
import patterns.trash.*;
import java.util.*;
2015-11-03 12:00:44 -08:00
import java.util.stream.*;
2015-06-15 17:47:35 -07:00
// Generic TypeMap works in any situation:
class TypeMap<T> {
private Map<Class,List<T>> t = new HashMap<>();
public void add(T o) {
Class type = o.getClass();
if(t.containsKey(type))
t.get(type).add(o);
else {
List<T> v = new ArrayList<>();
v.add(o);
t.put(type,v);
}
}
2015-11-03 12:00:44 -08:00
public Stream<List<T>> values() {
return t.values().stream();
2015-06-15 17:47:35 -07:00
}
}
2015-11-03 12:00:44 -08:00
// Adapter class for callbacks
// from ParseTrash.fillBin():
2015-06-15 17:47:35 -07:00
class TypeMapAdapter implements Fillable {
TypeMap<Trash> map;
2017-05-01 14:33:10 -06:00
TypeMapAdapter(TypeMap<Trash> tm) {
2015-06-15 17:47:35 -07:00
map = tm;
}
@Override
public void addTrash(Trash t) { map.add(t); }
}
public class DynaTrash {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
TypeMap<Trash> bin = new TypeMap<>();
2015-11-03 12:00:44 -08:00
ParseTrash.fillBin(
"trash", new TypeMapAdapter(bin));
bin.values().forEach(Trash::sumValue);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
2016-07-20 06:32:39 -06:00
/* Output: (First and Last 10 Lines)
2015-06-15 17:47:35 -07:00
Loading patterns.trash.Glass
Loading patterns.trash.Paper
Loading patterns.trash.Aluminum
Loading patterns.trash.Cardboard
weight of patterns.trash.Paper = 22.0
weight of patterns.trash.Paper = 11.0
weight of patterns.trash.Paper = 88.0
weight of patterns.trash.Paper = 91.0
weight of patterns.trash.Paper = 80.0
weight of patterns.trash.Paper = 66.0
2016-07-22 14:45:35 -06:00
...________...________...________...________...
weight of patterns.trash.Aluminum = 81.0
weight of patterns.trash.Aluminum = 36.0
weight of patterns.trash.Aluminum = 93.0
weight of patterns.trash.Aluminum = 36.0
Total value = 860.0499778985977
weight of patterns.trash.Cardboard = 96.0
weight of patterns.trash.Cardboard = 44.0
weight of patterns.trash.Cardboard = 12.0
weight of patterns.trash.Cardboard = 22.0
Total value = 40.02000072598457
2015-09-07 11:44:36 -06:00
*/