有没有更快的方法来使用Java查找不同的元素

use*_*493 1 java

我编写了代码来查找大量字符串中的distinct元素.代码如下

HashMap<String, Integer> countMap = new HashMap<>();
String[] str={"aa","bb","cc","bb","aa","cc","aa","bb","cc","bb"};
for (String e : str) {
  if (!countMap.containsKey(e)) {
    countMap.put(e, 1);
  } 
}
Iterator it=countMap.keySet().iterator();
String[] db= new String[countMap.size()];
for(int i=0;i<countMap.size();i++){
  db[i]=(String)it.next();
  System.out.println(db[i]);
}
Run Code Online (Sandbox Code Playgroud)

有没有比这更快的代码,因为我必须处理非常大的数组.

Mur*_*nik 5

这不会(相当)更快,但使用a HashSet肯定会更优雅:

String[] str={"aa","bb","cc","bb","aa","cc","aa","bb","cc","bb"};
Set<String> distinct = new HashSet<>(Arrays.asList(str));
for(String s : distinct) {
    System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)