开发者

Creating composite key for filtering data using Apache commons

开发者 https://www.devze.com 2023-01-05 21:19 出处:网络
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 \'k

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' I开发者_运维技巧s 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;
        }           
    });


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.


you can override the equals() in the exception class to check on the "compositeKey". then create a Set off the list (set.addAll()) and there you go. u have a unique set of exceptions

0

精彩评论

暂无评论...
验证码 换一张
取 消