【问题标题】:How can I use map in this kind of situation in grails?在 grails 的这种情况下如何使用 map ?
【发布时间】:2013-05-20 23:06:31
【问题描述】:

我需要显示在 ec2 上运行的服务器信息。我已经设法将它们显示为 json,但现在我只需要显示某些字段。下面显示了我如何显示statusCodeRunType。类似的概念也适用于其他领域。

  def check = reservations.each { Reservation reservation ->
        reservation.instances.each() { Instance instance ->
            def code = instance.state
            def StatusCode = code.code
//Get other values


            instance.tags.each() { Tag tag5 ->
                def KeyName2 = tag5.key;
                if (KeyName2 == 'RunType') {
                    def RunType = tag5.value;
                }
            }
       }

instance.tags.each() { Tag tag2 ->

                def KeyName2 = tag2.key;

                if (KeyName2 == 'RunType') {
                    def value2 = tag2.value;                    }
            }

            instance.tags.each() { Tag tag3 ->

                def KeyName3 = tag3.key;

                if (KeyName3 == 'StartedBy') {
                    def value = tag3.value;
                }
            } 

我想获得这样的东西来显示在我的 gsp 页面中并为每个服务器循环它。

def map = [StatusCode:"80", RunType:"Always", value"test", value2:"abc"]

但不确定当我通过代码获取值时如何向地图添加值

【问题讨论】:

  • 您能否编辑您的问题以添加您希望生成的地图的形状?
  • 那么,您想要地图列表吗?很难看出你拥有什么和想要什么......
  • 是的,我想你最终必须使用地图列表。请参阅下面的答案。
  • 也更新了我的答案 ;-)
  • 如果您仍然对实现持怀疑态度,请参阅此Sample Groovy Script 镜像您的用例。

标签: loops grails collections groovy hashmap


【解决方案1】:

你也许可以使用这个:

def result = reservations.collectMany { reservation ->
  reservation.instances.collect { instance ->
    [ StatusCode: instance.code,
      RunType   : instance.tags.find { it.key == 'RunType' }?.value,
      StartedBy : instance.tags.find { it.key == 'StartedBy' }?.value ]
  }
}

更新问题后更新

【讨论】:

    【解决方案2】:

    从代码来看,一个statusCode可以有多个value5。如果不是这种情况,那么您可以执行以下操作:

    def myList = []
    def check = reservations.each { Reservation reservation ->
                    reservation.instances.each() { Instance instance ->
                    def statusCode = instance.state?.code
                    def value5 = instance.tags?.find{it.key == 'RunType'}?.value
                    myList << ["StatusCode": statusCode, "RunType": value5 ]
               }
          }
    

    请注意,内部循环已简化。我不确定它是否符合您的用例场景,因为存在内部循环。如果您认为 map 需要在循环内向下移动一级,那么您也要在列表中维护一个键值对(或 map)列表。

    使用 groovy 的 collectinject 功能可以过度简化逻辑。

    【讨论】:

    • StatusCode 和 Value5 r 不同的字段,我想我把你弄糊涂了。 Value5 是运行类型。
    • 您能否在问题中显示一个结构化的虚拟地图,以了解您最终希望如何获得?
    • 类似于我在上面的地图
    • @TestUser 这些地图的列表?
    • 是的,因为大约有 50-60 台服务器,我认为我需要一个地图列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2015-11-30
    • 2017-05-16
    • 2012-10-06
    • 2011-05-18
    • 2019-11-29
    • 2022-01-23
    相关资源
    最近更新 更多