拆分字符串;然后比较这些值

时间:2016-04-28 20:17:50

标签: java string split compare java-7

我有一个字符串,它返回由;分隔的一堆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. 
}

如何比较每个值?

3 个答案:

答案 0 :(得分:5)

您可以将它们全部放在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!
}

答案 1 :(得分:2)

解决方案:

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

答案 2 :(得分:0)

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

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

相关问题