Purge unused realms

You can call the admin/realms endpoint and get a list of all realms.
Go over them and check against one of the properties you need.

The Keycloak REST API is not fully documented so it’s better to dive into the source code.
The keycloak-admin-client is the best resource in my opinion.
A couple of examples on how to use it Keycloak Admin Client in Spring Boot

You could just do the following based on the examples in the link I posted

RealmsResource realmsResource = keycloak.realms();
for (RealmRepresentation realmRepresentation : realmsResource.findAll()) {
    // Do your thing
}