I am having an arraylist of MyObjects in which i want to split my list based on the title value of my object.For Example
List<MyProduct> productList = instance.getMyProductList();
this is my list containing many products.
product = productList.get(i);
String tittle = product.getTitle();
I want to split my arraylist into several list which is having similar product title.
Please let me know. Thanks.
With Guava:
ListMultimap<String, MyProduct> result = Multimaps.index(productList, new Function<String, Product>() {
@Override
public String apply(Product input) {
return input.getTitle();
}
});
With plain old Java collections:
Map<String, List<MyProduct>> result = new HashMap<>();
for (MyProduct p : productList) {
List<MyProduct> list = result.get(p.getTitle());
if (list == null) {
list = new ArrayList<>();
result.put(p.getTitle(), list);
}
list.add(p);
}
Both assume that a "similar" title is actually an "equal" title.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With