【问题标题】:Split string by ; then compare the values按 ; 分割字符串然后比较值
【发布时间】:2016-04-28 20:17:49
【问题描述】:

我有一个字符串,它返回一组由; 分隔的 id。我正在拆分它们以获取它们各自的值以传递给另一个实用程序以查找父 ID。然后,我需要将父 ID 相互比较以确保所有 ID 都是相同的值。字符串可以包含一对多的 id。示例:

String unitIdList = "3e46907f-c4e8-44d2-8cab-4abb5a191a72;9d242306-1c7c-4c95-afde-e1057af9d67c;2e96838f-f0df-4c82-b5bc-cb81a6bdb792;b21a4b19-6c1a-4e74-aa84-7900f6ffa7a8"

for ( String unitIds : unitIdList.split(";") ) {
    parentId = UnitUtil.getInstance().getParentId(UUID.fromString(unitIds));

     // now I need to compare parentIds. They should all be the same, but if not then do something else. 
}

如何比较每个值?

【问题讨论】:

    标签: java string split compare java-7


    【解决方案1】:

    您可以将它们全部放在Set 中并检查大小是否为1

    String unitIdList = // ...
    Set<String> distinctIds = new HashSet<>(Arrays.asList(unitIdList.split(";")));
    if(distinctIds.size() == 1) {
        // all the same ids
    } else {
        // not all the same!
    }
    

    【讨论】:

    • 我需要比较每个 id 或每个元素,所以 3e46907f-c4e8-44d2-8cab-4abb5a191a72 EQUAL 9d242306-1c7c-4c95-afde-e1057af9d67c 等
    • 将项目添加到 Set 会自动删除重复项。
    【解决方案2】:

    解决方案:

    if (Stream.of(unitIdList.split(";")).distinct().count() == 1) {
        // only one distinct ID
    } else {
        // more than one distinct IDs
    }
    

    【讨论】:

      【解决方案3】:

      您可以拆分(就像您已经拥有的那样),然后循环遍历每个项目,与其他项目进行比较。

      String unitIdList = "3e46907f-c4e8-44d2-8cab-4abb5a191a72;9d242306-1c7c-4c95-afde-e1057af9d67c;2e96838f-f0df-4c82-b5bc-cb81a6bdb792;b21a4b19-6c1a-4e74-aa84-7900f6ffa7a8";
      
      String[] ids = unitIdList.split(";");
      
      boolean allEqual = true;
      
      for (String s1 : ids) {
          for (String s2 : ids) {
              allEqual = s1.equals(s2);
          }
      }
      
      System.out.println("eq: " + allEqual);
      
      if (allEqual) {
          // ...
      }
      

      这绝不是优化的。只要 allEqual 为 false,您就可以 break 退出两个循环。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-28
        • 2013-11-24
        相关资源
        最近更新 更多