簡體   English   中英

拆分字符串; 然后比較這些值

[英]Split string by ; then compare the values

我有一個字符串,返回一堆被分隔的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. 
}

我該如何比較每個值?

您可以將它們全部放入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!
}

解決方案:

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

您可以拆分(就像您已經擁有的那樣),然后遍歷每個項目,與其他項目進行比較。

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兩個循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM