0
votes

I'm having a cast error while trying a method. I couldn't figure out the actual problem here.

(List) member --> this line is generating cast error as class couldnt cast to List.

How can I update this issue?

java.lang.ClassCastException: com.test.Member cannot be cast to java.util.List at com.test.impl.Main.splitMembersByState

  protected Map< String, List< Member>> splitMembersByState(List< Member> validMembers) {
    // TODO

    Map< String, List< Member>> membersSplitByState = new HashMap<String, List<Member>>();
    List<Member> tempList = validMembers;

    for (Member member : validMembers) {
        membersSplitByState.put(member.getState(), (List<Member>) member);

    }

    return membersSplitByState;
  }

Thank you.

2
how can you cast a collection to a single element? You understand that List<Member> is a collection of 'Member' s?SomeDude
@svasa membersSplitByState.put(member.getState(), (List<Member>) member) I need to put single Member object in Map, while I place member there it suggests to cast to List. I'd couldn't solve this issue .Rajendra Maharjan

2 Answers

1
votes

membersSplitByState is String -> List and you're trying to put a member in it (member).

Here, you want to put your member in a list of members, not directly in the map. Something like that:

    Map< String, List< Member>> membersSplitByState = new HashMap<String, List<Member>>();
    List<Member> tempList = validMembers;

    for (Member member : validMembers) {
        List<Member> membersWithState;
        if (membersSplitByState.containsKey(member.getState()) {
           membersWithState = membersSplitByState.get(member.getState());
        } else {
           membersWithState = new ArrayList<Member>();
           membersSplitByState.put(member.getState(), membersWithState);
        }
        membersWithState.add(member);
    }
    return membersSplitByState;
1
votes

You cannot cast an Object(Element in your case) to a list of Object and hence the exception. Try replacing the for loop in your code with the following code:

 for (Member member : validMembers) {
            String key = member.getState();
            List<Member> newList = membersSplitByState.get(key);
            if(newList == null) {
             newList = new ArrayList<>();
             membersSplitByState.put(key, newList);
            }

            newList.add(member);

        }