Jason Jason - 7 months ago 12
Java Question

Split string by ; then compare the values

I have a string that returns a bunch of ids seperated by

;
. I am splitting them to get their individual values to pass to another utility to lookup a parent id. I then need to compare the parent ids to each other to make sure all ids are the same value. The string could contain one to many ids. Example:

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.
}


How can I compare each value?

Answer

You can put them all in a Set and check that the size is 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!
}
Comments