【问题标题】:How to get the MATCH value from MAP如何从 MAP 获取 MATCH 值
【发布时间】:2021-03-22 02:33:57
【问题描述】:

我正在尝试弄清楚如何获取匹配值并将其存储在字符串变量中,这就是我所做的:

出于示例目的,我创建了以下内容:

        Map<Attachment, String> mapattach = new HashMap<Attachment, String>();  
        Attachment a1 = new Attachment();
        a1.setId("one1");
        a1.setName("one");
        a1.setUrl("http://1.com");
    
        Attachment a2 = new Attachment();
        a2.setId("two2");
        a2.setName("two");
        a2.setUrl("http://2.com");
    
        Attachment a3 = new Attachment();
        a3.setId("three3");
        a3.setName("three");
        a3.setUrl("http://3.com");
    
        mapattach.put(a1, "one1");
        mapattach.put(a2, "two22");
        mapattach.put(a3, "three33");

        //java stream
        //it will match only one item and it returns
        String matchFound = mapattach.entrySet().stream()
            .filter( f -> recordIds.contains(f.getKey().getId()))
            .findFirst().toString();

以上代码返回一条记录的字符串:

结果:

 Optional[class Attachment {
     name: one
     id: one1
     mimeType: null
     url: http://1.com
     referenceId: null }=one1]

但我想要的只是url 我该怎么办?

【问题讨论】:

    标签: stream java-stream


    【解决方案1】:

    你快到了,这应该可以解决问题:

        Optional<String> optionalUrl = mapattach.entrySet().stream()
                .filter(f -> recordIds.contains(f.getKey().getId()))
                .findFirst()
                .map(attachmentStringEntry -> attachmentStringEntry.getKey().getUrl());
        
        urlMatchFound = optionalUrl.get(); // remember that it might not be present.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多