繁体   English   中英

同一个键下有多个值的HashMap

[英]HashMap with multiple values under the same key

我们是否可以实现一个键和两个值的HashMap。 就像 HashMap 一样?

请帮助我,也告诉(如果没有办法)任何其他方式来实现以一个为键的三个值的存储?

你可以:

  1. 使用具有列表作为值的地图。 Map<KeyType, List<ValueType>>
  2. 创建一个新的包装器类并将此包装器的实例放置在地图中。 Map<KeyType, WrapperType>
  3. 使用类似类的元组(节省创建大量包装器)。 Map<KeyType, Tuple<Value1Type, Value2Type>>
  4. 并排使用多个地图。

例子

1. 以列表为值映射

// create our map
Map<String, List<Person>> peopleByForename = new HashMap<>();    

// populate it
List<Person> people = new ArrayList<>();
people.add(new Person("Bob Smith"));
people.add(new Person("Bob Jones"));
peopleByForename.put("Bob", people);

// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];

这种方法的缺点是列表不绑定到两个值。

2. 使用包装类

// define our wrapper
class Wrapper {
    public Wrapper(Person person1, Person person2) {
       this.person1 = person1;
       this.person2 = person2;
    }

    public Person getPerson1 { return this.person1; }
    public Person getPerson2 { return this.person2; }

    private Person person1;
    private Person person2;
}

// create our map
Map<String, Wrapper> peopleByForename = new HashMap<>();

// populate it
Wrapper people = new Wrapper();
peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"),
                                        new Person("Bob Jones"));

// read from it
Wrapper bobs = peopleByForename.get("Bob");
Person bob1 = bobs.getPerson1;
Person bob2 = bobs.getPerson2;

这种方法的缺点是您必须为所有这些非常简单的容器类编写大量样板代码。

3. 使用元组

// you'll have to write or download a Tuple class in Java, (.NET ships with one)

// create our map
Map<String, Tuple2<Person, Person> peopleByForename = new HashMap<>();

// populate it
peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith",
                                       new Person("Bob Jones"));

// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;

这是我认为最好的解决方案。

4. 多张地图

// create our maps
Map<String, Person> firstPersonByForename = new HashMap<>();
Map<String, Person> secondPersonByForename = new HashMap<>();

// populate them
firstPersonByForename.put("Bob", new Person("Bob Smith"));
secondPersonByForename.put("Bob", new Person("Bob Jones"));

// read from them
Person bob1 = firstPersonByForename["Bob"];
Person bob2 = secondPersonByForename["Bob"];

此解决方案的缺点是两个地图相关性并不明显,编程错误可能会导致两个地图不同步。

不,不仅仅是作为HashMap 您基本上需要一个从键到值集合的HashMap

如果你乐于使用外部库, GuavaMultimap有这个概念,有ArrayListMultimapHashMultimapLinkedHashMultimap等实现。

Multimap<String, Integer> nameToNumbers = HashMultimap.create();

System.out.println(nameToNumbers.put("Ann", 5)); // true
System.out.println(nameToNumbers.put("Ann", 5)); // false
nameToNumbers.put("Ann", 6);
nameToNumbers.put("Sam", 7);

System.out.println(nameToNumbers.size()); // 3
System.out.println(nameToNumbers.keySet().size()); // 2

另一个不错的选择是使用 Apache Commons 中的MultiValuedMap 查看页面顶部的所有已知实现类,了解专门的实现。

示例:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

可以替换为

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

所以,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

将导致集合coll包含“A”、“B”和“C”。

从番石榴库中查看Multimap及其实现 - HashMultimap

类似于 Map 的集合,但可以将多个值与单个键相关联。 如果使用相同的键但不同的值调用 put(K, V) 两次,则多重映射包含从键到两个值的映射。

我使用Map<KeyType, Object[]>将多个值与 Map 中的一个键相关联。 这样,我可以存储与一个键关联的不同类型的多个值。 您必须小心维护从 Object[] 插入和检索的正确顺序。

示例:考虑,我们要存储学生信息。 键是 id,而我们想存储与学生关联的姓名、地址和电子邮件。

       //To make entry into Map
        Map<Integer, String[]> studenMap = new HashMap<Integer, String[]>();
        String[] studentInformationArray = new String[]{"name", "address", "email"};
        int studenId = 1;
        studenMap.put(studenId, studentInformationArray);

        //To retrieve values from Map
        String name = studenMap.get(studenId)[1];
        String address = studenMap.get(studenId)[2];
        String email = studenMap.get(studenId)[3];
HashMap<Integer,ArrayList<String>> map = new    HashMap<Integer,ArrayList<String>>();

ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);

如果您使用Spring 框架 有: org.springframework.util.MultiValueMap

创建不可修改的多值映射:

Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);

或者使用org.springframework.util.LinkedMultiValueMap

只是为了记录,纯 JDK8 解决方案是使用Map::compute方法:

map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);

比如

public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();

    put(map, "first", "hello");
    put(map, "first", "foo");
    put(map, "bar", "foo");
    put(map, "first", "hello");

    map.forEach((s, strings) -> {
        System.out.print(s + ": ");
        System.out.println(strings.stream().collect(Collectors.joining(", ")));
    });
}

private static <KEY, VALUE> void put(Map<KEY, List<VALUE>> map, KEY key, VALUE value) {
    map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
}

带输出:

bar: foo
first: hello, foo, hello

请注意,为了确保在多个线程访问此数据结构时的一致性,例如需要使用ConcurrentHashMapCopyOnWriteArrayList

最简单的方法是使用谷歌收藏库:

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Test {

    public static void main(final String[] args) {

        // multimap can handle one key with a list of values
        final Multimap<String, String> cars = ArrayListMultimap.create();
        cars.put("Nissan", "Qashqai");
        cars.put("Nissan", "Juke");
        cars.put("Bmw", "M3");
        cars.put("Bmw", "330E");
        cars.put("Bmw", "X6");
        cars.put("Bmw", "X5");

        cars.get("Bmw").forEach(System.out::println);

        // It will print the:
        // M3
        // 330E
        // X6
        // X5
    }

}

Maven 链接: https : //mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2

更多相关信息: http : //tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html

是和否。 解决方案是为您的值构建一个 Wrapper 类,其中包含与您的键对应的 2 个(3 个或更多)值。

String key= "services_servicename"

ArrayList<String> data;

for(int i = 0; i lessthen data.size(); i++) {
    HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
    servicesNameHashmap.put(key,data.get(i).getServiceName());
    mServiceNameArray.add(i,servicesNameHashmap);
}

我得到了最好的结果。

你只需要像这样创建新的HashMap

HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();

在你的for循环中。 它将具有相同的键和多个值的相同效果。

使用 Java 收集器

// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));

部门是你的关键

 import java.io.*;
 import java.util.*;

 import com.google.common.collect.*;

 class finTech{
public static void main(String args[]){
       Multimap<String, String> multimap = ArrayListMultimap.create();
       multimap.put("1","11");
       multimap.put("1","14");
       multimap.put("1","12");
       multimap.put("1","13");
       multimap.put("11","111");
       multimap.put("12","121");
        System.out.println(multimap);
        System.out.println(multimap.get("11"));
   }                                                                                            
 }                                                                    

输出:

     {"1"=["11","12","13","14"],"11"=["111"],"12"=["121"]}

      ["111"]

这是用于实用功能的 Google-Guava 库。 这是必需的解决方案。

我无法对 Paul 的评论发表回复,所以我在这里为 Vidhya 创建新评论:

Wrapper 将是我们要存储为值的两个类的SuperClass

在包装类中,我们可以将关联作为两个类对象的实例变量对象。

例如

class MyWrapper {

 Class1 class1obj = new Class1();
 Class2 class2obj = new Class2();
...
}

HashMap 中我们可以这样放置

Map<KeyObject, WrapperObject> 

WrapperObj将有类变量: class1Obj, class2Obj

你可以隐式地做到这一点。

// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();

//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });

//edit value of a key
map.get(1)[0] = "othername";

这是非常简单和有效的。 如果您想要不同类的值,您可以执行以下操作:

HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();

可以使用 identityHashMap 来完成,条件是键比较将由 == 运算符而不是 equals() 完成。

我更喜欢以下内容来存储任意数量的变量,而不必创建单独的类。

final public static Map<String, Map<String, Float>> myMap    = new HashMap<String, Map<String, Float>>();

我已经习惯于在 Objective C 中使用数据字典来做这件事。在 Android 的 Java 中很难获得类似的结果。 我最终创建了一个自定义类,然后只是对我的自定义类做了一个哈希图。

public class Test1 {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addview);

//create the datastring
    HashMap<Integer, myClass> hm = new HashMap<Integer, myClass>();
    hm.put(1, new myClass("Car", "Small", 3000));
    hm.put(2, new myClass("Truck", "Large", 4000));
    hm.put(3, new myClass("Motorcycle", "Small", 1000));

//pull the datastring back for a specific item.
//also can edit the data using the set methods.  this just shows getting it for display.
    myClass test1 = hm.get(1);
    String testitem = test1.getItem();
    int testprice = test1.getPrice();
    Log.i("Class Info Example",testitem+Integer.toString(testprice));
}
}

//custom class.  You could make it public to use on several activities, or just include in the activity if using only here
class myClass{
    private String item;
    private String type;
    private int price;

    public myClass(String itm, String ty, int pr){
        this.item = itm;
        this.price = pr;
        this.type = ty;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getType() {
        return item;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}

我们可以创建一个具有多个键或值的类,这个类的对象可以用作映射中的参数。 可以参考https://stackoverflow.com/a/44181931/8065321

Apache Commons 集合类可以在同一个键下实现多个值。

MultiMap multiMapDemo = new MultiValueMap();

multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");

System.out.println(multiMapDemo.get("fruit"));

Maven 依赖

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.4</version>
</dependency>

我们是否可以用一个键和两个值来实现HashMap。 就像HashMap一样?

还请告诉我(如果没有办法)通过其他任何方法来实现三个值的存储(以一个为键)的方法,对我有帮助吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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