实体类实现根据指定属性进行排序

1、实体类



import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;

import org.appdot.model.IdEntity;


@Table(name = "tw_media")
@Entity
public class Media extends IdEntity implements Comparable<Media> {

	protected String url;

	protected MediaType mediaType;

	protected Integer displayOrder;

	@Column(name = "url")
	public String getUrl() {
		return url;
	}

	@Enumerated(EnumType.STRING)
	@Column(name = "media_type")
	public MediaType getMediaType() {
		return mediaType;
	}

	@Column(name = "display_order")
	public Integer getDisplayOrder() {
		return displayOrder;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setMediaType(MediaType mediaType) {
		this.mediaType = mediaType;
	}

	public void setDisplayOrder(Integer displayOrder) {
		this.displayOrder = displayOrder;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Media [url=").append(url).append(", mediaType=").append(mediaType).append(", displayOrder=")
				.append(displayOrder).append("]");
		return builder.toString();
	}

	public static enum MediaType {
		IMAGE
	}

	@Override
	public int compareTo(Media o) {
		Integer otherDisplayOrder = o.displayOrder;
		if (otherDisplayOrder == null) {
			return 1;
		}
		if (displayOrder == null) {
			return -1;
		}
		return displayOrder.compareTo(otherDisplayOrder);
	}
}

2、取出实体集合后需要调用sort()

***********代码片段***********

Set<Media> medias = company.getImages();

			List<Media> tmpList = new ArrayList<Media>();
			Iterator<Media> iterator = medias.iterator();
			while (iterator.hasNext()) {
				Media tmp = iterator.next();
				tmpList.add(tmp);
			}
			Comparator<Media> mycmp = ComparableComparator.getInstance();
                       //默认升序
                       //mycmp = ComparatorUtils.reversedComparator(mycmp); // 逆序
                        Comparator cmp = new BeanComparator("displayOrder", mycmp);
			Collections.sort(tmpList, cmp);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值