HashSet和HapMap取distinct value

时间:2023-03-09 00:32:30
HashSet和HapMap取distinct value

public class TestHashSetAndHashMap {

private final int setNum=5000;

@Test
public void doTest(){

List<Set<Long>> testList=new ArrayList<Set<Long>>();
for(int i=0;i<setNum;i++){
Set<Long> testSet =new HashSet<Long>();
for(int j=0;j<setNum;j++){
testSet.add((long) (i+j));
}
testList.add(testSet);
}

HashMap<Long,Long> map=new HashMap<Long,Long>();

{
long start=System.currentTimeMillis();
for(Set<Long> each:testList){
for(Long id:each){
map.put(id,id);
}
}

System.out.println("cost1="+(System.currentTimeMillis()-start));
System.out.println("map="+map.size());
}

{
Set<Long> allSet=new HashSet<Long>();
long start=System.currentTimeMillis();

for(Set<Long> each:testList){

allSet.addAll(each);
}

System.out.println("cost2="+(System.currentTimeMillis()-start));
System.out.println("allSet="+allSet.size());
}

}

}

结果是

cost1=1216
map=9999
cost2=1136
allSet=9999