Реализация Map с делает дубликаты ключа

Вы можете связать свою кнопку, используя PlacementTarget

<Button BorderThickness="1" Visibility="Visible" Command="{*..and now I want to bind my command...*}" DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"/>

. Позже в коде вам нужно указать тег, он ищет окно, но вы можете изменить anecestorType.

<TextBox Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

Конечно, в вашей ViewModel (DataContext) вы должны указать правильную команду.

105
задан Matthias Braun 13 March 2018 в 14:35
поделиться

7 ответов

You are searching for a multimap, and indeed both commons-collections and Guava have several implementations for that. Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection.

If you can use Java 5, I would prefer Guava's Multimap as it is generics-aware.

86
ответ дан 24 November 2019 в 03:59
поделиться

Никакое воображение не освобождает требуемый. Карты определяются уникальным ключом, не изгибайте их, используйте список. Потоки являются могущественными.

import java.util.AbstractMap.SimpleImmutableEntry;

List<SimpleImmutableEntry<String, String>> nameToLocationMap = Arrays.asList(
    new SimpleImmutableEntry<>("A", "A1"),
    new SimpleImmutableEntry<>("A", "A2"),
    new SimpleImmutableEntry<>("B", "B1"),
    new SimpleImmutableEntry<>("B", "B1"),
);

И вот именно. Примеры использования:

List<String> allBsLocations = nameToLocationMap.stream()
        .filter(x -> x.getKey().equals("B"))
        .map(x -> x.getValue())
        .collect(Collectors.toList());

nameToLocationMap.stream().forEach(x -> 
do stuff with: x.getKey()...x.getValue()...
1
ответ дан 24 November 2019 в 03:59
поделиться

Если есть дубликаты keys, то ключ может соответствовать более чем одному значению. Очевидное решение - сопоставить ключ со списком этих значений.

Например, в Python:

map = dict()
map["driver"] = list()
map["driver"].append("john")
map["driver"].append("mike")
print map["driver"]          # It shows john and mike
print map["driver"][0]       # It shows john
print map["driver"][1]       # It shows mike
0
ответ дан 24 November 2019 в 03:59
поделиться

для полноты: Apache Commons Collections также имеет MultiMap . Обратной стороной, конечно же, является то, что Apache Commons не использует Generics.

0
ответ дан 24 November 2019 в 03:59
поделиться

Could you also explain the context for which you are trying to implement a map with duplicate keys? I am sure there could be a better solution. Maps are intended to keep unique keys for good reason. Though if you really wanted to do it; you can always extend the class write a simple custom map class which has a collision mitigation function and would enable you to keep multiple entries with same keys.

Note: You must implement collision mitigation function such that, colliding keys are converted to unique set "always". Something simple like, appending key with object hashcode or something?

0
ответ дан 24 November 2019 в 03:59
поделиться

If you want iterate about a list of key-value-pairs (as you wrote in the comment), then a List or an array should be better. First combine your keys and values:

public class Pair
{
   public Class1 key;
   public Class2 value;

   public Pair(Class1 key, Class2 value)
   {
      this.key = key;
      this.value = value;
   }

}

Replace Class1 and Class2 with the types you want to use for keys and values.

Now you can put them into an array or a list and iterate over them:

Pair[] pairs = new Pair[10];
...
for (Pair pair : pairs)
{
   ...
}
10
ответ дан 24 November 2019 в 03:59
поделиться

You could simply pass an array of values for the value in a regular HashMap, thus simulating duplicate keys, and it would be up to you to decide what data to use.

You may also just use a MultiMap, although I do not like the idea of duplicate keys myself.

17
ответ дан 24 November 2019 в 03:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: