将一个list对象数组按照指定的规则排序

时间:2021-01-06 06:54:14

方法一

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

public PageInfo<Member> findPage(Long styleId,Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
MemberDesignerBean memberDesignerBean = new MemberDesignerBean();
memberDesignerBean.setStyleId(styleId);
List<MemberDesigner> list = memberDesignerDao.list(memberDesignerBean);
if(CollectionUtils.isEmpty(list)){
return null;
}
PageInfo<MemberDesigner> pageInfo = new PageInfo<MemberDesigner>(list);

//将一个List<MemberDesigner>中的id单独提取出来。这个id在数组中是有序的,在后面需要用到。
final List<Long> idList = Lists.transform(list, new Function<MemberDesigner, Long>() {
@Override
public Long apply(MemberDesigner input) {
return input.getMemberId();
}
});

//得到一个无序的List<Member>,按照上面的idList进行排序。
List<Member> designers = memberDao.listByIdList(idList);
Collections.sort(designers, new Comparator<Member>(){
@Override
public int compare(Member o1, Member o2) {
if (o1 == null) {
return -1;
} else if (o2 == null) {
return 1;
}
int s1index = idList.indexOf(o1.getId());
int s2index = idList.indexOf(o2.getId());
return s1index > s2index ? 1 : -1;
}});

return PageInfoUtil.buildNewPageInfo(pageInfo, designers);
}
方法二

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.FixedOrderComparator;

public PageInfo<Member> findPage(Long styleId,Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
MemberDesignerBean memberDesignerBean = new MemberDesignerBean();
memberDesignerBean.setStyleId(styleId);
List<MemberDesigner> list = memberDesignerDao.list(memberDesignerBean);
if(CollectionUtils.isEmpty(list)){
return null;
}
PageInfo<MemberDesigner> pageInfo = new PageInfo<MemberDesigner>(list);
List<Long> idList = BizUtil.extractToList(list, "memberId");
List<Member> designers = memberDao.listByIdList(idList);
designers = BizUtil.sortList("id", designers, idList);
return PageInfoUtil.buildNewPageInfo(pageInfo, designers);
}

/**
* list根据某个属性给定的集合排序
*
* @param propertyName 属性名
* @param list 需要排序的list
* @param from 属性对应的集合值
* @return list 排序后的list
*
*/
public static <T,F> List<T> sortList(String propertyName, List<T> list,List<F> from) {
FixedOrderComparator fixedOrderComparator = new FixedOrderComparator(from);
Comparator<T> comparator = new BeanComparator<T>(propertyName,fixedOrderComparator);
Collections.sort(list,comparator);
return list;
}