我有一个hashmap,其中的条目如下:
HashMap<HashSet<String>, Long> mapping = new HashMap<>();
aaa.bb.cc.d, aaa.bb.cc, gg.hh.ee, aaa.bb, 34523
fff.kk.mmmm.ft, iiii.pp.cds, fff.kk, aaa.b, 4343
tpks.tt.po.d, tpks.tt.po, tpks.tt, aa.bb, 544670
运行代码后的结果应如下所示:
1st entry key should go in nesteds_2 : aaa.bb.cc.d, gg.hh.ee
2nd entry key should go in nesteds_3 : fff.kk.mmm.ft, iiii.pp.cds, aaa.b
3rd entry key should go in nesteds_2 : tpks.tt.po.d, aa.bb
etc.
哈希集中的字符串都是按长度降序排列的。每当一个字符串包含另一个字符串时,只需要较长的字符串。如果任何字符串包含在另一个字符串中,即哈希集中的字符串小于4,则应将其从哈希集中删除并存储到相应的数组中。然后必须从hashmap中删除整个条目。
public class Edit {
public void edit(HashMap<HashSet<String>, Long> hm){
List<String> li;
String _1,_2,_3,_4;
ArrayList<String> nesteds = new ArrayList<>();
ArrayList<String> nesteds_2 = new ArrayList<>();
ArrayList<String> nesteds_3 = new ArrayList<>();
for(Iterator<Map.Entry<HashSet<String>, Long>> it = hm.entrySet().iterator(); it.hasNext(); ) {
li = new ArrayList<String>((Collection<? extends String>) it.next().getKey());
Comparator<String> stringLengthComparator = new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return Integer.compare(o2.length(), o1.length());
}
};
Collections.sort(li, stringLengthComparator);
_1 = li.get(0);
_2 = li.get(1);
_3 = li.get(2);
_4 = li.get(3);
if(_1.contains(_2)){
li.remove(_2);
if(_1.contains(_3)){
li.remove(_3);
if(_1.contains(_4)){
li.remove(_4);
}
}
}else{
if(_1.contains(_3) || _2.contains(_3)){
li.remove(_3);
if(_2.contains(_4) || _2.contains(_4)){
li.remove(_4);
}
}else{
if(_3.contains(_4) || _1.contains(_4) || _2.contains(_4)){
li.remove(_4);
}
}
}
System.out.println(li.toString());
}
}
}