Search code examples
javaapache-commons

Creating composite key for filtering data using Apache commons


Here is my problem I have a list of 'System Exceptions' and I need to select distinct values from the list based on two keys. So I am creating a compositeKey and storing it in a list as a string 'key1:key2' Is there a better approach to this ?

    Collection uniqueExceptions = CollectionUtils.select(allSubareaExceptions, new Predicate(){
        private List<String> ids = new ArrayList<String>();
        public boolean evaluate(Object obj) {
            ....domain.Exception ex = (....domain.Exception)obj;
            String compositeKey = ex.getProcedure().getSubarea().getId() +":"+ex.getProcedure().getId();
            if(ids.contains(compositeKey) == false){
                ids.add(compositeKey);
                return true;
            }
            return false;
        }           
    });

Solution

  • There are several options. You could create a list:

     List<String> compositKey = Arrays.asList(getSubareaId(), getProcedureId());
    

    You could use an AbstractMap.SimpleEntry (1.6 or later only):

    SimpleEntry<String, String> compositKey = new SimpleEntry(getSubareaId(), getProcedureId());
    

    You could create your own pair implementation, or even a composite key class.

    The major danger of using concatenation is if : is a legal character in the id strings, then you could get false duplicates.