原文地址https://blog.csdn.net/u013399093/article/details/47749823
原文地址https://blog.csdn.net/tjcyjd/article/details/6872471
1.HashSet
java.util.HashSet類實現了Java.util.Set接口。
它有如下特點:
1.它不允許出現重複元素-----------無重複
2.不保證集合中元素的順序---------無序
3.允許包含值爲null的元素,但最多隻能有一個null元素。
下面代碼是利用hashSet獲取不重複的一組groupId:
- public static List<Long> getGroups(List<Resource> resourceList) {
- Set<Long> set = new HashSet();
- for (Resource resource : resourceList) {
- if (StringUtils.isNotBlank(resource.groupIds)) {
- for (String groupId : StringUtils.split(resource.groupIds, ",")) {
- if (StringUtils.isNotBlank(groupId)) {
- set.add(Long.parseLong(groupId));
- }
- }
- }
- }
- return new ArrayList<Long>(set);
- }
2.TreeSet
TreeSet是可以實現排序等功能的集合,它在對象元素添加到集合中時會自動按照某種比較規則將其插入到有序的對象序列中;
TreeSet是如何對對象進行排序的捏? TreeSet支持 兩種排序方式: 自然排序和客戶化排序, 默認情況下是自然排序.
在JDK中,有一部分類實現了Comparable接口,如Integer,Double和String等,Comparable接口有一個compareTo(Object o)方法,
它返回整數類型,對於表達式x.compareTo(y),如果返回值爲0,表示x和y相等,如果返回值大於0,表示x大於y,如果小於0,表示x TreeSet調用對象的compareTo()方法比較集合中對象的大小,然後進行升序排序,這種方式稱爲自然排序.
客戶化排序:
java.util.Comparator接口用於指定具體的排序方式,它有個compare(Object obj1,Object obj2),用於比較兩個對象的大小.
當表達式compare(x,y)的值大於0,表示x大於y,小於0,表示x小於y,等於0,表示x等於y,如果想讓TreeSet進按照Customer對象的
name屬性進行降序排列,可以先創建實現Comparator接口的類CustomerComparator,如:
import java.util.*;
public class CustomerComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
Customer c1=(Custoemr)o1;
Customer c2=(Customer)o2;
if(c1.getName().compareTo(c2.getName())>0) return -1;
if(c1.getName().compareTo(c2.getName())<0) return 1;
return 0;
}
}
接下來在構造TreeSet的實例時,調用它的TreeSet(Comparator comparator)構造方法
Set set=new TreeSet(new CustomerComparator());
Customer c1=new Customer("TOM",15);
Customer c2=new Customer("JACK",20);
Customer c3=new Customer("MIKE",38);
set.add(c1);set.add(c2);set.add(c3);
Iterator it=set.iterator();
while(it.hasNext())
{Custoemr customer=(Customer)it.next();
System.out.println(customer.getName()+"" +customer.getAge();)
}
當TreeSet向集合中加入Customer對象時,會調用CustomerComparator類的compare()方法進行排序,以上Tree按照
Custoemr對象的name屬性進行降序排列,最後輸出爲:
TOM 15 MIKE 38 JACK 16
============================================================================================================================
Set的最大特點是能去掉重複的元素並獲取相應數據,下面看個簡單的代碼,先使用QBC查詢出所有員工,在過濾掉重複的員工所在部門,最後得到所有員工的部門串:
- List<Employee> list = employeeDAO.findByExample(employee);
- Set set = new HashSet();
- for (int i = 0; i < list.size(); i++) {
- set.add(list.get(i).getDepartmentId());
- }
- String deptIds = "";
- Iterator it = set.iterator();
- while (it.hasNext()) {
- deptIds = "'" + it.next().toString() + "',";
- }