0

Can you please help me to construct Hashmap with Objects from ArrayList.

public class Store {

    private int storeId;
    private String storeName;
    private int deliveryDays;
    private List<String> servingZipCodes;
    private StoreAddress storeAddress;


    public Store() {
    }

    public Store(int storeId,String storeName,int deliveryDays,List<String> servingZipCodes,StoreAddress storeAddress){
        this.storeId = storeId;
        this.storeName=storeName;
        this.deliveryDays=deliveryDays;
        this.servingZipCodes=servingZipCodes;
        this.storeAddress = storeAddress;
    }

//getters and setters.
}

And the StoreAddress class

public class StoreAddress {

    private String streetAddress1;
    private String streetAddress2;
    private String streetAddress3;
    private String city;
    private String state;
    private String postalCode;
    private String country;
    private String phone;

    public StoreAddress() {
    }

    public StoreAddress(String streetAddress1, String streetAddress2, String streetAddress3, String city, String state, String postalCode, String country, String phone) {
        this.streetAddress1 = streetAddress1;
        this.streetAddress2 = streetAddress2;
        this.streetAddress3 = streetAddress3;
        this.city = city;
        this.state = state;
        this.postalCode = postalCode;
        this.country = country;
        this.phone = phone;
    }

Here is the Test class to for testing.

public class Test {

    public static void main(String args[]){

        List<Store> storeList=new ArrayList();
        StoreAddress storeAddress1 = new StoreAddress("1500 Polaris Pkwy",null,null,"Columbus","OH","43240","US","9165452345");
        StoreAddress storeAddress2 = new StoreAddress("160 Easton Town Center",null,null,"Columbus","OH","43240","US","9165452345");
        storeList.add(new Store(1,"Store 1",7,new ArrayList<String>(Arrays.asList("43240","43241","43242")),storeAddress1));
        storeList.add(new Store(2,"Store 2",7,new ArrayList<String>(Arrays.asList("43240","43082","43081")),storeAddress2));
        Map<String,List<Store>> zipCodeStoreList = null;
        storeList.forEach(store -> {
            List<String> servingZipCodes = store.getServingZipCodes();
            servingZipCodes.stream().filter(x -> x.matches(store.getStoreAddress().getPostalCode().substring(0,5))).map(x ->new HashMap<String, Object>(){{
                put(x, store);
            }});
        });

Though its possible in Java 7 but looking for solutions in java 8.

Key: 43240, value: Store1 , Store2
Key: 43241, value: null
Key: 43242, value: null
Key: 43082, value: null
Key: 43081, value: null
7
  • This map's keyset is supposed to be each served zip code, and each value should be the list of stores that serve that zip code? Commented Jul 14, 2017 at 18:39
  • Yes thats one I am looking for Commented Jul 14, 2017 at 18:43
  • 1
    you should know what are you doing at first rather than how. Indeed, you must find out the intersection of zipCodes between Stores, and then building the Map base on the intersection of zipCodes. Commented Jul 14, 2017 at 18:50
  • Thanks !! let try that way Commented Jul 14, 2017 at 18:58
  • Does it have to be a HashMap? Commented Jul 14, 2017 at 19:02

2 Answers 2

2

As I said you should thinking of what are you doing first rather than how, then the problem is easy to solve. and then you can obtain self-describing code, for example:

//             v--- union all zip codes from stores
Stream<String> union = storeList.stream().map(Store::getServingZipCodes)
                                         .flatMap(List::stream)
                                         .distinct();

//             v--- find out intersections between zip codes
Stream<String> intersection = union.filter(zip ->
        storeList.stream().map(Store::getServingZipCodes)
                          .allMatch(it -> it.contains(zip))
);

//                       v--- create a Map simply from intersections 
Map<String, List<Store>> result = intersection.collect(toMap(
        Function.identity(),
        unused -> storeList
));

Output

assert result.get("43240") == [store1, store2];
assert result.get("others") == null;
Sign up to request clarification or add additional context in comments.

Comments

0

What I did is first, filter the List for Stores with a given zip code. This given zip code is the variable name key. I then use the key to put the resulting filter into the Map variable zipCodeStoreList.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @author blj0011
 */
public class Test
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        List<Store> storeList=new ArrayList();
        StoreAddress storeAddress1 = new StoreAddress("1500 Polaris Pkwy",null,null,"Columbus","OH","43240","US","9165452345");
        StoreAddress storeAddress2 = new StoreAddress("160 Easton Town Center",null,null,"Columbus","OH","43240","US","9165452345");

        storeList.add(new Store(1,"Store 1",7,new ArrayList(Arrays.asList("43240","43241","43242")),storeAddress1));
        storeList.add(new Store(2,"Store 2",7,new ArrayList(Arrays.asList("43240","43082","43081")),storeAddress2));
        Map<String,List<Store>> zipCodeStoreList = new HashMap();

        String key = "43241";//See if a Store associates with this zip code.
        //Add the key and the results from filtering the storeList based on the key.
        zipCodeStoreList.put(key, storeList.stream().filter(x -> x.getServingZipCodes().contains(key)).collect(Collectors.toList()));
        //Print results
        for(Map.Entry<String, List<Store>> entry : zipCodeStoreList.entrySet())
        {
            for(Store store : entry.getValue())
            {
                System.out.println("filter 1: " + entry.getKey() + " - " + store.getStoreName());
            }
        }        
    }

}

enter image description here enter image description here enter image description here

Altered Version that lists all of the Stores associated with a particular zip code.

Remove

    String key = "43081";
    zipCodeStoreList.put(key, storeList.stream().filter(x -> x.getServingZipCodes().contains(key)).collect(Collectors.toList()));

Replace with

    //Add the zip code belong to at least one store plus a zip code that belongs to no store.
    List<String> allZipCodes = new ArrayList(Arrays.asList("43240","43082","43081", "43240","43241","43242", "55555"));
    for(String zipCode : allZipCodes)
    {
        zipCodeStoreList.put(zipCode, storeList.stream().filter(x -> x.getServingZipCodes().contains(zipCode)).collect(Collectors.toList()));
    }

enter image description here

2 Comments

Thanks all let me implement
You can copy the text of the output panel into your browser; there is no need to do a screenshot and upload pictures.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.