簡體   English   中英

從使用 List 作為值的 HashMap 中刪除 object

[英]Remove object from a HashMap that use List as values

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

如何從列表中刪除播放器 object? 我現在的代碼是:

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

但我想只用一行來改進。

您是否希望:

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

編輯

這個問題有點不清楚,因為我會提出這個解決方案,所以如果你想從包含它的第一個元素中刪除ObjectIWantToRemove ,那么你可以像這樣使用 stream :

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

你可以做的一件事是:

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

這將避免在刪除元素之前調用contains

如果你想在一行中完成,你可以這樣做:

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

這會將玩家從它所屬的所有團隊中刪除,而上面的解決方案僅將其從第一個團隊中刪除。

如果您正在尋找一種僅從第一個中刪除它的解決方案,那么已經有了答案。

嘗試這個。

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

如果團隊包含ObjectIWantToRemove ,則 List.remove List.remove(Object)返回 true。 此表達式僅選擇包含ObjectIWantToRemove的第一個團隊。

這使用整數和字符串來演示,但也可以應用於您的類。

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);

印刷

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]

盡管這會刪除所有對象,但我會假設(可能是錯誤的)一個球員不會為同一支球隊列出兩次。 如果您只想刪除遇到的第一個,請使用此構造。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM