【问题标题】:how to store and compare unique pairs in java? which data structure is useful?如何在java中存储和比较唯一对?哪种数据结构有用?
【发布时间】:2017-01-29 11:26:04
【问题描述】:

我有一个通知对象的列表,它的名字是通知。我将它映射到一个 HashMap 中:

Map<String, String> recipientByMedia = new HashMap<>();
        for (Notification obj : notifications) {
            recipientByMedia.put(obj.getMedia(), obj.getRecipient());
        }

我的通知列表对“IM”有两个不同的值:

"IM" : "+928292929"
"IM" : "test@yahoo.com"

我知道,HashMap 会覆盖新的“IM”而不是最旧的。最后,我想用这个 HashMap 在 "Mockoto.assertEqual" 中使用。像这样:

assertEquals(recipientByMedia.get("IM"), contact.getSmsNumber());
assertEquals(recipientByMedia.get("IM"), contact.getImAddress());

其中一项测试将失败。如何在测试中比较“IM”?我可以使用哪种数据结构来代替 HashMap?

【问题讨论】:

    标签: java collections hashmap


    【解决方案1】:

    我认为,它是哈希映射的一个特性,它在域和范围之间建立了一对一的关系。

    我建议你制作不同的钥匙。喜欢

    assertEquals(recipientByMedia.get("IM0"), contact.getSmsNumber());
    assertEquals(recipientByMedia.get("IM1"), contact.getImAddress());
    

    【讨论】:

      【解决方案2】:

      既然类Notification 似乎是唯一的事实来源,为什么需要不同的数据结构?你想用Map 完成什么?

      如果您想在列表中查找Notification 对象的属性,其中getMedia 假设为"IM",您可以过滤列表并直接从用于保存它的对象访问属性信息种类:

      String recipient = notifications.stream()
        .filter(n -> "IM".equals(n.getMedia()))
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException(/* not in the list */))
        .getRecipient();
      

      如果不是这种情况,并且您想组合来自多个来源的数据,请创建 POJOs 以用于保存必要信息的确切目的,或者如果更易读,则只需使用 2 个数据源来获取组合信息出于某种目的。

      【讨论】:

        【解决方案3】:

        使用 setter 和 getter 创建一个模型,然后使用 ArrayList 而不是像这样的 Hashmap private ArrayList&lt;StudentsDetail&gt; arraylist;,然后在你的 for 循环中添加这个 arraylist.add(new StudensDetail(obj.getMedia(), obj.getRecipient()));,当你想要获取值时,在你的 for 循环中写下这段代码 @987654323 @

        这就是模型

        public class StudentDetails {
        private String name;
        private String id;
        
        public StudentDetails(String name, String id) {
            this.name = name;
            this.id = id;
        }
        
        public String getName() {
            return name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
        
        public String getId() {
            return id;
        }
        
        public void setId(String id) {
            this.id = id;
        }
        

        }

        【讨论】:

        • 谢谢。太好了。但是,我怎样才能比较这些价值???? “IM”有两个值,我想测试这两个值。我该怎么办????
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多