从List <Map>检索数据

时间:2019-06-09 13:56:02

标签: java parsing java-stream

我使用流Stream<Map<String, Object>> sub = ipfs.pubsub.sub(topic)订阅了一个主题,然后将其收集到一个列表中,该列表将收集前两个结果List<Map> results = sub.limit(2).collect(Collectors.toList());并在以后进行解析 通过results.stream().filter(s->s.containsKey("data")).forEach(System.out::println);返回以下输出

{from=EiANvs2UUz/KwtJhTJIgOdUPvsNeVF74GczENrlC4UCFVQ==, data=SGVsbG8h, seqno=FaaJ6v+WW+g=, topicIDs=[demo134001007467618]}
{from=EiANvs2UUz/KwtJhTJIgOdUPvsNeVF74GczENrlC4UCFVQ==, data=RydkYXk=, seqno=FaaJ6v+WW+k=, topicIDs=[demo134001007467618]}

现在我应该如何从列表中获取每个值,以便可以在本地变量上分配它们?

//Full block of code
public void pubsub() throws Exception {
       String topic = "demo" + System.nanoTime();
       Stream<Map<String, Object>> sub = ipfs.pubsub.sub(topic);
       String data = "Hello!";
       Object pub = ipfs.pubsub.pub(topic, data);
       Object pub2 = ipfs.pubsub.pub(topic, "G'day");
       List<Map> results = sub.limit(2).collect(Collectors.toList());
       results.stream().filter(s->s.containsKey("data")).forEach(System.out::println);
}

1 个答案:

答案 0 :(得分:0)

解决了解析问题:

 public void pubsub2() throws Exception {
        String topic = "demo" + System.nanoTime();
        Stream<Map<String, Object>> sub = ipfs.pubsub.sub(topic); 
        String data = "Hello!"; 
        Object pub = ipfs.pubsub.pub(topic, data); 
        Object pub2 = ipfs.pubsub.pub(topic, "G'day"); 
        List<Map> results = sub.limit(2).collect(Collectors.toList());

   for (int index = 0; index< results.size(); index++ ) {
            Map<String, String> listItem = results.get(index);
            System.out.println(listItem);
            Iterator it = listItem.entrySet().iterator();
                while(it.hasNext()){
                    Map.Entry pair = (Map.Entry) it.next();
                    System.out.println(pair.getKey()+" = " + pair.getValue());
                }