简体   繁体   中英

Remove object from a HashMap that use List as values

private static final Map<TeamType, List<Player>> LIST = new ConcurrentHashMap<>();

How can i remove a Player object from the LIST? My code right now is:

for (List<Player> team : LIST.values())
{
    if (team.contains(ObjectIWantToRemove))
    {
        team.remove(ObjectIWantToRemove);
        return;
    }
}

But i want to improve using just a single line.

Are you looking to:

LIST.values().forEach(team -> team.remove(ObjectIWantToRemove));

Edit

The question is a little unclear, for that I will put this solution, so if you want to remove ObjectIWantToRemove from the first element which contain it, then you can use stream like this:

LIST.values().stream()
        .filter(team -> team.contains(ObjectIWantToRemove))
        .findFirst()
        .ifPresent(team -> team.remove(ObjectIWantToRemove));

One thing you could do is this:

for (List<Player> team : LIST.values()) {
     if (team.remove(ObjectIWantToRemove))
     {
         return;
     }
}

This will avoid the call to contains before removing the element.

If you want to do it in one line, you can do it like that:

LIST.values().forEach(team -> team.remove(ObjectIWantToRemove));

That will remove the player from all teams it belongs to, whereas the solution above only remove it from the first one.

If you are looking for a solution that removes it only from the first, there already is an answer.

Try this.

LIST.values().stream().filter(team -> team.remove(ObjectIWantToRemove)).findFirst();

List.remove(Object) returns true if the team contained the ObjectIWantToRemove . This expression selects only the first team that contain ObjectIWantToRemove .

This uses Integers and Strings to demonstrate but could also be applied to your classes.

LIST.put("A", new ArrayList<>(List.of(1,2,3,4,2,3,1)));
LIST.put("B", new ArrayList<>(List.of(1,2, 9, 10,2)));
LIST.put("C", new ArrayList<>(List.of(1,2,5,2, 9, 1)));
LIST.put("D", new ArrayList<>(List.of(1,3,2,4,2)));


Integer ObjectToRemove = 2;

System.out.println("Before remove");
LIST.entrySet().forEach(System.out::println);


LIST.forEach((k,v)->v.removeIf(r->r.equals(ObjectToRemove)));

System.out.println("After remove");
LIST.entrySet().forEach(System.out::println);

Prints

Before remove
A=[1, 2, 3, 4, 2, 3, 1]
B=[1, 2, 9, 10, 2]
C=[1, 2, 5, 2, 9, 1]
D=[1, 3, 2, 4, 2]
After remove
A=[1, 3, 4, 3, 1]
B=[1, 9, 10]
C=[1, 5, 9, 1]
D=[1, 3, 4]

Even though this removes all Objects, I would assume (perhaps wrongly) that a player would not be listed twice for the same team. If you just want to remove the first one encountered, then use this construct.

LIST.forEach((k,v)->v.remove(ObjectToRemove));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM