根据id去重,方法一
List<BaseTreeNode> treeNodes=bulidTree(); //去重 treeNodes = treeNodes.stream().collect(Collectors .collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(n -> n.getId()))), ArrayList::new) );根据id去重,方法二
//去重 List<BaseTreeNode> treeNodes=bulidTree(); treeNodes = treeNodes.stream().collect(Collectors.collectingAndThen( Collectors.toCollection( () -> new TreeSet<>((o1, o2) -> { if (o1.getId().compareTo(o2.getId()) == 0) { return 0; } else { return o1.getId().compareTo(o2.getId()); } })), ArrayList::new) );根据true和false排序,false在前,true在后,方法如下
//排序 Collections.sort(treeNodes, new Comparator<BaseTreeNode>() { public int compare(BaseTreeNode o1, BaseTreeNode o2) { boolean onLine1 = o1.getLeaf(); boolean onLine2 = o2.getLeaf(); if (onLine1 ^ onLine2) { return onLine1 ? 1 : -1; } else { return 0; } } });根据true和false排序,false在前,true在后;再根据某个对象类型二次排序
//排序 Collections.sort(treeNodes, new Comparator<BaseTreeNode>() { public int compare(BaseTreeNode o1, BaseTreeNode o2) { boolean onLine1 = o1.getLeaf(); boolean onLine2 = o2.getLeaf(); if (onLine1 ^ onLine2) { return onLine1 ? 1 : -1; } else { return 0; } } }.thenComparing(new Comparator<BaseTreeNode>() { public int compare(BaseTreeNode o1, BaseTreeNode o2) { if (o1 instanceof Company && o2 instanceof Organization) { return -1; } if (o1 instanceof Organization && o2 instanceof Company) { return 1; } return 0; } }));普通排序一
排序一 //升序排列 List<MasterProperty> masterPropertys=findAll(); Collections.sort(masterPropertys, new Comparator<MasterProperty>() { @Override public int compare(MasterProperty o1, MasterProperty o2) { return o1.getOrder() - o2.getOrder(); } }); 排序二 //升序排列 List<MasterProperty> masterPropertys=findAll(); Collections.sort(masterPropertys, (o1, o2) -> o1.getOrder().compareTo(o2.getOrder())); 排序三 //升序排列 List<MasterProperty> masterPropertys=findAll(); Collections.sort(masterPropertys, Comparator.comparing( MasterProperty::getOrder, (o1, o2) -> { return o1.compareTo(o2); }));普通排序二
排序一 List<ComUnit> comUnitList = comUnitService.findAll(); //排序 Collections.sort(comUnitList, Comparator.comparing(ComUnit::getOrder)); 排序二 List<ComUnit> comUnitList = comUnitService.findAll(spec); //排序 comUnitList.sort(Comparator.comparing(ComUnit::getOrder));Comparator.reversed ,返回相反的排序规则
List<MasterProperty> masterPropertys=findAll(); masterPropertys.sort(Comparator.comparing(MasterProperty::getOrder).reversed());注:
当前对象与后一个对象进行比较,如果比较结果为1进行交换,其他不进行交换。
当后一个对象比当前对象大,返回结果值为1时,前后交换,说明是倒序排列。
当后一个对象比当前对象小,返回结果值为1时,前后交换,说明是升序排列