使用TreeSet和Comparator,写TreeSetTest2 要求:对TreeSet中的元素1,2,3,4,5,6,7,8,9,10进行排列,排序逻辑为奇数在前偶数在后,奇数按照升序排列,偶数按照降序排列
/*
* 使用TreeSet和Comparator,写TreeSetTest2
*要求:对TreeSet中的元素1,2,3,4,5,6,7,8,9,10进行排列,
*排序逻辑为奇数在前偶数在后,奇数按照升序排列,偶数按照降序排列
*/
import java.util.Comparator;
import java.util.TreeSet;
public class TreeTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<Integer> treeSet = new TreeSet<>(new SetComparator());
//treeSet.add(-1);
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
treeSet.add(6);
treeSet.add(7);
treeSet.add(8);
treeSet.add(9);
treeSet.add(10);
System.out.println(treeSet);
for (Integer integer : treeSet) {
System.out.print(integer+" ");
}
}
}
class SetComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if(o1%2==1&&o2%2==0) {
return -1;
}
if(o1%2==0&&o2%2==1) {
return 1;
}
if (o1%2==1&&o2%2==1) {
return o1-o2;
}
if (o1%2==0&&o2%2==0) {
return o2-o1;
}
return 0;
}
}
/* * 使用TreeSet和Comparator,写TreeSetTest2 *要求:对TreeSet中的元素1,2,3,4,5,6,7,8,9,10进行排列, *排序逻辑为奇数在前偶数在后,奇数按照升序排列,偶数按照降序排列 */import java.util.Comparator;import java.util.TreeSet;
public class TreeTest2 {
public static void main(String[] args) {// TODO Auto-generated method stubTreeSet<Integer> treeSet = new TreeSet<>(new SetComparator());//treeSet.add(-1);treeSet.add(1);treeSet.add(2);treeSet.add(3);treeSet.add(4);treeSet.add(5);treeSet.add(6);treeSet.add(7);treeSet.add(8);treeSet.add(9);treeSet.add(10);System.out.println(treeSet);for (Integer integer : treeSet) {System.out.print(integer+" ");}}
}class SetComparator implements Comparator<Integer>{
@Overridepublic int compare(Integer o1, Integer o2) {// TODO Auto-generated method stubif(o1%2==1&&o2%2==0) {return -1;}if(o1%2==0&&o2%2==1) {return 1;}if (o1%2==1&&o2%2==1) {return o1-o2;}if (o1%2==0&&o2%2==0) {return o2-o1;}return 0;}}