Given a List
of items of different types, how do I efficiently separate those, so each group only contains item of the same type?
More details
In java, I have a List
of about 10000 items. There are 10 different types of item. Type as in property of value. For example, List<Foo>
, then type is Foo#getType()
.
I need to create zip-files that contain only one type of item.
Please give me some idea. Code are most-welcomed and appreciated, even pseudo-code. Thank you.
Accepted Code taking the idea from Jon Skeet
List<Foo> list = ...;
ImmutableListMultimap<String, Foo> grouped = MultiMaps.index(list,
new Function<Foo, String>() {
public String apply(Foo input) {
return input.getType();
}
});
for(String type : grouped.keySet()){
//The below list will contains items with the same type.
ImmutableList<Foo> fooListWithSameType = grouped.get(type);
String zipName = getZipName(type);
//Zip the list to a given file name
zipList(foo开发者_如何学CListWithSameType, zipName);
}
You could use Guava's MultiMap
functionality with MultiMaps.index
, so using your Foo.getType()
example, if it returns a string:
ImmutableListMultimap<String, Foo> grouped = MultiMaps.index(list,
new Function<Foo, String>() {
public String apply(Foo input) {
return input.getType();
}
});
Jon's answer will let you sort them by type into a new in-memory structure, but if you just need zip files per type, why not
Map<Type, ZipOutputStream> zips = ...;
for (Foo foo : list) {
zips.get(foo.getType())... // add the entry and write the content
}
Build a map from type to a set of objects of that type. Iterate the list and add each object to the appropriate bucket.
If you want a solution that uses less memory, you can sort the list by type to group the objects in chunks containing items of the same type.
精彩评论