Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split ArrayList into multipleList based on the value in the list

Tags:

java

arraylist

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.

like image 317
AndroidCrazy Avatar asked Mar 28 '26 01:03

AndroidCrazy


1 Answers

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.

like image 176
JB Nizet Avatar answered Mar 29 '26 13:03

JB Nizet