Is there a better way to combine two string sets in java?

后端 未结 12 1317
天涯浪人
天涯浪人 2020-12-05 01:41

I need to combine two string sets while filtering out redundant information, this is the solution I came up with, is there a better way that anyone can suggest? Perhaps som

12条回答
  •  旧时难觅i
    2020-12-05 02:25

    If you care about performance, and if you don't need to keep your two sets and one of them can be huge, I would suggest to check which set is the largest and add the elements from the smallest.

    Set newStringSet = getNewStringSet();
    Set oldStringSet = getOldStringSet();
    
    Set myResult;
    if(oldStringSet.size() > newStringSet.size()){
        oldStringSet.addAll(newStringSet);
        myResult = oldStringSet;
    } else{
        newStringSet.addAll(oldStringSet);
        myResult = newStringSet;
    }
    

    In this way, if your new set has 10 elements and your old set has 100 000, you only do 10 operations instead of 100 000.

提交回复
热议问题