Collection_Compare

冒泡

package com.bjsxt.sort.bubble;

import java.util.Arrays;

public class BubbleSort1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] arr ={9,8,7,6,5};
        sort(arr);

    }
    //第一版本,很简单
    public static void sort(int[] arr){
        int len =arr.length;
        for(int j=0;j<len-1;j++){
            System.out.println("第"+(j+1)+"趟");
            for(int i=0;i<len-1;i++){
                System.out.print("第"+(i+1)+"次");
                if(arr[i]>arr[i+1]){
                    int temp = arr[i];
                    arr[i] =arr[i+1];
                    arr[i+1] =temp;
                }
                System.out.println(Arrays.toString(arr));
            }
        }
    }
    public static void sortSecond(int[] arr){
        System.out.println("第一趟");
        for(int i=0;i<arr.length-1;i++){
            System.out.print("第"+(i+1)+"次");
            if(arr[i]>arr[i+1]){
                int temp = arr[i];
                arr[i] =arr[i+1];
                arr[i+1] =temp;
            }
            System.out.println(Arrays.toString(arr));
        }
        System.out.println("第二趟");
        for(int i=0;i<arr.length-1;i++){
            System.out.print("第"+(i+1)+"次");
            if(arr[i]>arr[i+1]){
                int temp = arr[i];
                arr[i] =arr[i+1];
                arr[i+1] =temp;
            }
            System.out.println(Arrays.toString(arr));
        }
        System.out.println("第三趟");
        for(int i=0;i<arr.length-1;i++){
            System.out.print("第"+(i+1)+"次");
            if(arr[i]>arr[i+1]){
                int temp = arr[i];
                arr[i] =arr[i+1];
                arr[i+1] =temp;
            }
            System.out.println(Arrays.toString(arr));
        }
        System.out.println("第四趟");
        for(int i=0;i<arr.length-1;i++){
            System.out.print("第"+(i+1)+"次");
            if(arr[i]>arr[i+1]){
                int temp = arr[i];
                arr[i] =arr[i+1];
                arr[i+1] =temp;
            }
            System.out.println(Arrays.toString(arr));
        }

    }

    public static void sortFirst(int[] arr){
        System.out.println("第一趟");
        for(int i=0;i<arr.length-1;i++){
            System.out.print("第"+(i+1)+"次");
            if(arr[i]>arr[i+1]){
                int temp = arr[i];
                arr[i] =arr[i+1];
                arr[i+1] =temp;
            }
            System.out.println(Arrays.toString(arr));
        }

        /*
        //第一趟 第一次
        System.out.println("第一趟 第一次");
        int i=0;
        if(arr[i]>arr[i+1]){
            int temp = arr[i];
            arr[i] =arr[i+1];
            arr[i+1] =temp;
        }
        System.out.println(Arrays.toString(arr));
        System.out.println("第一趟 第二次");
        i++;
        if(arr[i]>arr[i+1]){
            int temp = arr[i];
            arr[i] =arr[i+1];
            arr[i+1] =temp;
        }
        System.out.println(Arrays.toString(arr));

        System.out.println("第一趟 第三次");
        i++;
        if(arr[i]>arr[i+1]){
            int temp = arr[i];
            arr[i] =arr[i+1];
            arr[i+1] =temp;
        }
        System.out.println(Arrays.toString(arr));

        System.out.println("第一趟 第四次");
        i++;
        if(arr[i]>arr[i+1]){
            int temp = arr[i];
            arr[i] =arr[i+1];
            arr[i+1] =temp;
        }
        System.out.println(Arrays.toString(arr));

        */
    }

}
package com.bjsxt.sort.bubble;

import java.util.Arrays;

public class BubbleSort2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] arr ={9,8,7,6,5};
        sort(arr);
    }
    //第二版本,减少每一趟的次数
    public static void sort(int[] arr){
            int len =arr.length;
            for(int j=0;j<len-1;j++){ //趟数
                System.out.println("第"+(j+1)+"趟");
                for(int i=0;i<len-1-j;i++){ //次数
                    System.out.print("第"+(i+1)+"次");
                    if(arr[i]>arr[i+1]){
                        int temp = arr[i];
                        arr[i] =arr[i+1];
                        arr[i+1] =temp;
                    }
                    System.out.println(Arrays.toString(arr));
                }
            }
        }

}
package com.bjsxt.sort.bubble;

import java.util.Arrays;

/**
 * 最终版本:考虑存在顺序
 * @author Administrator
 *
 */
public class BubbleSort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] arr ={1,2,9,3,4};
        sort1(arr);

        System.out.println("==========final============");
        arr =new int[]{9,1,2,3,4};
        sortFinal(arr);
    }
    //第二版本,减少每一趟的次数
    public static void sortFinal(int[] arr){
            boolean sorted= true;
            int len =arr.length;
            for(int j=0;j<len-1;j++){ //趟数
                sorted =true; //假定有序
                for(int i=0;i<len-1-j;i++){ //次数
                    if(arr[i]>arr[i+1]){
                        int temp = arr[i];
                        arr[i] =arr[i+1];
                        arr[i+1] =temp;
                        sorted =false; //假定失败
                    }
                    System.out.println(Arrays.toString(arr));
                }
                if(sorted){ //减少趟数
                    break;
                }
            }
        }

    //第二版本,减少每一趟的次数
    public static void sort1(int[] arr){
            int len =arr.length;
            for(int j=0;j<len-1;j++){ //趟数
                System.out.println("第"+(j+1)+"趟");
                for(int i=0;i<len-1-j;i++){ //次数
                    System.out.print("第"+(i+1)+"次");
                    if(arr[i]>arr[i+1]){
                        int temp = arr[i];
                        arr[i] =arr[i+1];
                        arr[i+1] =temp;
                    }
                    System.out.println(Arrays.toString(arr));
                }
            }
        }

}

引用数据类型:

1.整数小数Integer Float Double直接比较基本数据类型的大小

2.比较unicode码之差

3.字符串:

package com.bjsxt.sort.innerType;
/**
 * 内置引用数据类型(常用)的比较
 * @author Administrator
 *
 */
public class Demo01 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Integer  a ; //根据基本数据类型大小
        Character ch; //根据Unicode编码顺序
        String str="abc"; //如果其中一个是例外一个起始开始的子串,返回长度之差
        String str2 ="abcd123";  //否则返回第一个不相等的unicode码之差
        System.out.println(str.compareTo(str2));
        str ="abc";
        str2 ="aad";
        System.out.println(str.compareTo(str2));

        java.util.Date d ;  //根据日期的长整形数比较
    }

}

字符串的冒泡:

/**
     * @param args
     */
    public static void main(String[] args) {
        String[] arr ={"a","abcd","abc","def"};
        //从到小排序 降序
        boolean sorted= true;
        int len =arr.length;
        for(int j=0;j<len-1;j++){ //趟数
            sorted =true; //假定有序
            for(int i=0;i<len-1-j;i++){ //次数
                if(((Comparable)arr[i]).compareTo(arr[i+1])<0){
                    String temp = arr[i];
                    arr[i] =arr[i+1];
                    arr[i+1] =temp;
                    sorted =false; //假定失败
                }
            }
            if(sorted){ //减少趟数
                break;
            }
        }

        System.out.println(Arrays.toString(arr));
    }

时间的冒泡:

/**
     * @param args
     */
    public static void main(String[] args) {
        Date[] arr =new Date[3];
        arr[0] =new Date();
        arr[1] =new Date(System.currentTimeMillis()-1000*60*60);
        arr[2] =new Date(System.currentTimeMillis()+1000*60*60);
        //降序

        //从大到小排序 降序
            boolean sorted= true;
            int len =arr.length;
            for(int j=0;j<len-1;j++){ //趟数
                sorted =true; //假定有序
                for(int i=0;i<len-1-j;i++){ //次数
                    if(((Comparable)arr[i]).compareTo(arr[i+1])<0){
                        Date temp = arr[i];
                        arr[i] =arr[i+1];
                        arr[i+1] =temp;
                        sorted =false; //假定失败
                    }
                }
                if(sorted){ //减少趟数
                    break;
                }
            }

            System.out.println(Arrays.toString(arr));
    }

封装+泛型之后:

package com.bjsxt.sort.innerType;

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

/**
 * 排序
 * @author Administrator
 *
 */
public class Utils {
    /**
     * List的排序+比较器
     * @param list
     * @param com
     */
    public static  <T> void sort(List<T> list,Comparator<T> com){
        //第一步:转成数组
        Object[] arr =list.toArray();
        sort(arr,com);
        //第二步:改变容器中对应的值
        for(int i=0;i<arr.length;i++){
            list.set(i, (T)(arr[i]));
        }
    }

    /**
     * 数组的排序 (降序)+Comparator接口
     * @param arr
     */
    public static <T> void sort(Object[] arr,Comparator<T> com){
        //从大到小排序 降序
            boolean sorted= true;
            int len =arr.length;
            for(int j=0;j<len-1;j++){ //趟数
                sorted =true; //假定有序
                for(int i=0;i<len-1-j;i++){ //次数
                    if(com.compare((T)arr[i], (T)arr[i+1])<0){
                        Object temp = arr[i];
                        arr[i] =arr[i+1];
                        arr[i+1] =temp;
                        sorted =false; //假定失败
                    }
                }
                if(sorted){ //减少趟数
                    break;
                }
            }
    }

    /**
     * 容器排序 (使用泛型方法)
     */
    public static <T extends Comparable<T>> void sort(List<T> list){
        //第一步:转成数组
        Object[] arr =list.toArray();
        sort(arr);
        //第二步:改变容器中对应的值
        for(int i=0;i<arr.length;i++){
            list.set(i, (T)(arr[i]));
        }

    }

    /**
     * 数组排序 (使用泛型方法)
     */
    public static <T extends Comparable<T>> void sort(T[] arr){
        //从大到小排序 降序
        boolean sorted= true;
        int len =arr.length;
        for(int j=0;j<len-1;j++){ //趟数
            sorted =true; //假定有序
            for(int i=0;i<len-1-j;i++){ //次数
                if(((Comparable)arr[i]).compareTo(arr[i+1])<0){
                    T temp = arr[i];
                    arr[i] =arr[i+1];
                    arr[i+1] =temp;
                    sorted =false; //假定失败
                }
            }
            if(sorted){ //减少趟数
                break;
            }
        }
    }    

    /**
     * 数组的排序 (降序)
     * @param arr
     */
    public static void sort(Object[] arr){
        //从大到小排序 降序
        boolean sorted= true;
        int len =arr.length;
        for(int j=0;j<len-1;j++){ //趟数
            sorted =true; //假定有序
            for(int i=0;i<len-1-j;i++){ //次数
                if(((Comparable)arr[i]).compareTo(arr[i+1])<0){
                    Object temp = arr[i];
                    arr[i] =arr[i+1];
                    arr[i+1] =temp;
                    sorted =false; //假定失败
                }
            }
            if(sorted){ //减少趟数
                break;
            }
        }

    }

}

实例:

package com.bjsxt.sort.innerType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class Demo04 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Date[] arr =new Date[3];
        arr[0] =new Date();
        arr[1] =new Date(System.currentTimeMillis()-1000*60*60);
        arr[2] =new Date(System.currentTimeMillis()+1000*60*60);
        Utils.sort(arr); //降序
        System.out.println(Arrays.toString(arr));

        //字符串
        String[] arr2 ={"a","abcd","abc","def"};
        Utils.sort(arr2);
        System.out.println(Arrays.toString(arr2));

        System.out.println("==========List排序===========");
        //存放容器中
        List<String> list =new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        Utils.sort(list);
        System.out.println(list);

        System.out.println("==========使用Comparator 排序数组===============");
        arr2 =new String[]{"a","abcd","abc","def"};
        Utils.sort(arr2,new StringComp());
        System.out.println(Arrays.toString(arr2));

        System.out.println("==========List排序+比较器===========");
        list =new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        Utils.sort(list,new StringComp());
        System.out.println(list);

    }

}

方法而:实现java.util.Comparator接口

package com.bjsxt.sort.innerType;
/**
 * 排序规则的业务类
 * @author Administrator
 *
 */
public class StringComp  implements java.util.Comparator<String>{

    /**
     * 按长度比较大小
     * 正数 >
     * 负数 <
     * 0 ==
     */
    @Override
    public int compare(String o1, String o2) {
        int len1 =o1.length();
        int len2 =o2.length();
        return -(len1-len2);
    }

}
package com.bjsxt.sort.innerType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 使用Collections对容器的比较
 * 1、 public static <T> void sort(List<T> list, Comparator<? super T> c)
 * 2、public static <T extends Comparable<? super T>> void sort(List<T> list)
 * void sort(List<T> list)
 * @author Administrator
 *
 */
public class Demo05 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<String> list =new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        Collections.sort(list,new StringComp());
        System.out.println(list);

        list =new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        Collections.sort(list);
        System.out.println(list);

    }

}

新闻条目的排序:

package com.bjsxt.sort.refType;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 新闻条目实体类
 * @author Administrator
 *
 */
public class NewsItem implements java.lang.Comparable<NewsItem>{
    //标题
    private String title;
    //点击量
    private int hits;
    //时间
    private Date pubTime;
    public NewsItem() {
    }

    public NewsItem(String title, int hits, Date pubTime) {
        super();
        this.title = title;
        this.hits = hits;
        this.pubTime = pubTime;
    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public int getHits() {
        return hits;
    }
    public void setHits(int hits) {
        this.hits = hits;
    }
    public Date getPubTime() {
        return pubTime;
    }
    public void setPubTime(Date pubTime) {
        this.pubTime = pubTime;
    }

    //时间降序 +点击量升序+标题降序
    @Override
    public int compareTo(NewsItem o) {
        int result =0;
        //比较 时间
        result =-this.pubTime.compareTo(o.pubTime); //降序
        if(0==result){ //时间相同
            //点击量
            result =this.hits-o.hits; //升序
            if(0==result){ //点击量相同
                 //标题
                result=-this.title.compareTo(o.title);//降序
            }
        }        

        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb =new StringBuilder();
        sb.append("标题:").append(this.title);
        sb.append(",时间:").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this.pubTime));
        sb.append(",点击量:").append(this.hits).append("\n");
        return sb.toString();
    }

}
package com.bjsxt.sort.refType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.bjsxt.sort.innerType.Utils;

/**
 * 使用Collections
 * @author Administrator
 *
 */
public class NewsItemApp {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<NewsItem> news=new ArrayList<NewsItem>();
        news.add(new NewsItem("美国后怕了,逃跑了悲剧了",50,new Date(System.currentTimeMillis()-1000*60*60)));
        news.add(new NewsItem("中国登上钓鱼岛了,全国欢呼了",100,new Date()));
        news.add(new NewsItem("小日本终于听话了,泪流满面笑了",60,new Date(System.currentTimeMillis()-1000*60*60)));
        System.out.println("排序前:"+news);
        //排序
        //Collections.sort(news);
        Utils.sort(news);
        System.out.println("排序后"+news);

    }

}

商品的排序:

package com.bjsxt.sort.refType;
/**
 * 实体类
 * @author Administrator
 *
 */
public class Goods {
    //商品名称
    private String name;
    //价格
    private double price;
    //收藏量
    private int fav;
    public Goods() {
        // TODO Auto-generated constructor stub
    }

    public Goods(String name, double price, int fav) {
        super();
        this.name = name;
        this.price = price;
        this.fav = fav;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getFav() {
        return fav;
    }
    public void setFav(int fav) {
        this.fav = fav;
    }

    @Override
    public String toString() {
        return "商品名:"+name+",收藏量"+this.fav+",价格:"+this.price+"\n";
    }
}
package com.bjsxt.sort.refType;
/**
 * 按价格排序的业务类 (降序)
 * @author Administrator
 *
 */
public class GoodsPriceComp implements java.util.Comparator<Goods> {

    @Override
    public int compare(Goods o1, Goods o2) {
        return -(o1.getPrice()-o2.getPrice()>0?1:(o1.getPrice()==o2.getPrice()?0:-1));
    }

}
package com.bjsxt.sort.refType;
/**
 * 按收藏量排序的业务类 (升序)
 * @author Administrator
 *
 */
public class GoodsFavComp implements java.util.Comparator<Goods> {

    @Override
    public int compare(Goods o1, Goods o2) {
        return o1.getFav()-o2.getFav();
    }

}
package com.bjsxt.sort.refType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GoodsApp {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<Goods> list =new ArrayList<Goods>();
        list.add(new Goods("老马视频",100,2000));
        list.add(new Goods("老高视频",50,2000));
        list.add(new Goods("老裴视频",1000,1000));
        System.out.println("排序前:"+list);
    //    Collections.sort(list,new GoodsPriceComp());
        Collections.sort(list,new GoodsFavComp());
        System.out.println("排序后:"+list);
    }

}

TreeSet:

注意:在添加数据是排序,数据更改不会影响原来的属性

package com.bjsxt.sort.col;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Person {
    private final String name;//名称
    private final int handsome;//帅气指数

    public Person() {
        name =null;
        handsome =0;
    }

    public Person(String name, int handsome) {
        super();
        this.name = name;
        this.handsome = handsome;
    }

    public String getName() {
        return name;
    }

    public int getHandsome() {
        return handsome;
    }

    @Override
    public String toString() {
        return "姓名:"+this.name+",帅气指数:"+this.handsome+"\n";
    }

}
package com.bjsxt.sort.col;

import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Person p1 =new Person("您",100);
        Person p2 =new Person("刘德华",1000);
        Person p3 =new Person("梁朝伟",1200);
        Person p4 =new Person("老裴",50);

        TreeMap<Person,String> map =new TreeMap<Person,String>(new java.util.Comparator<Person>(){

            @Override
            public int compare(Person o1, Person o2) {
                return -(o1.getHandsome()-o2.getHandsome());
            }

        } );
        map.put(p1, "bjsxt");
        map.put(p2, "bjsxt");
        map.put(p3, "bjsxt");
        map.put(p4, "bjsxt");

        //查看键
        Set<Person> persons =map.keySet();
        System.out.println(persons);
    }

}
package com.bjsxt.sort.col;

public class Worker implements java.lang.Comparable<Worker> {
    //工种
    private String type;
    //工资
    private double salary;
    public Worker() {
        // TODO Auto-generated constructor stub
    }

    public Worker(String type, double salary) {
        super();
        this.type = type;
        this.salary = salary;
    }

    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }

    /**
     * 按工资升序
     */
    @Override
    public int compareTo(Worker o) {
        return this.salary>o.salary?1:( this.salary==o.salary?0:-1);
    }

    @Override
    public String toString() {
        return "工种:"+this.type+",工资:"+this.salary+"\n";
    }

}
package com.bjsxt.sort.col;

import java.util.TreeSet;
/**
 * 实体类实现Comparable 接口的应用
 * @author Administrator
 *
 */
public class TreeSetDemo2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Worker w1 =new Worker("垃圾回收员",12000);
        Worker w2 =new Worker("农民工",8000);
        Worker w3 =new Worker("程序猿",5000);

        TreeSet<Worker> employees =new TreeSet<Worker>();
        employees.add(w1);
        employees.add(w2);
        employees.add(w3);
        System.out.println(employees);

    }

}

TreeMap:

package com.bjsxt.sort.col;

import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Person p1 =new Person("您",100);
        Person p2 =new Person("刘德华",1000);
        Person p3 =new Person("梁朝伟",1200);
        Person p4 =new Person("老裴",50);

        TreeMap<Person,String> map =new TreeMap<Person,String>(new java.util.Comparator<Person>(){

            @Override
            public int compare(Person o1, Person o2) {
                return -(o1.getHandsome()-o2.getHandsome());
            }

        } );
        map.put(p1, "bjsxt");
        map.put(p2, "bjsxt");
        map.put(p3, "bjsxt");
        map.put(p4, "bjsxt");

        //查看键
        Set<Person> persons =map.keySet();
        System.out.println(persons);
    }

}
package com.bjsxt.sort.col;

import java.util.TreeMap;

public class TreeMapDemo02 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Worker w1 =new Worker("垃圾回收员",12000);
        Worker w2 =new Worker("农民工",8000);
        Worker w3 =new Worker("程序猿",5000);

        TreeMap<Worker,String > employees =new TreeMap<Worker,String >();
        employees.put(w1,"bjsxt");
        employees.put(w2,"bjsxt");
        employees.put(w3,"bjsxt");
        System.out.println(employees.keySet());
    }

}

Collections 的相关方法:

package com.bjsxt.sort.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *1、 binarySearch(List<? extends Comparable<? super T>> list, T key)   容器有序
 *2、sort(List<T> list)
     sort(List<T> list, Comparator<? super T> c)
 *3、reverse(List<?> list)
  4、shuffle(List<?> list) 洗牌
  5、swap(List<?> list, int i, int j)
 * @author Administrator
 *
 */
public class CollectionsDemo01 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<Integer> cards =new ArrayList<Integer>();
        //shuffle 洗牌 模拟斗地主
        for(int i=0;i<54;i++){
            cards.add(i);
        }
        //洗牌
        Collections.shuffle(cards) ;
        //依次发牌
        List<Integer> p1 =new ArrayList<Integer>();
        List<Integer> p2 =new ArrayList<Integer>();
        List<Integer> p3 =new ArrayList<Integer>();
        List<Integer> last =new ArrayList<Integer>();
        for(int i=0;i<51;i+=3){
            p1.add(cards.get(i));
            p2.add(cards.get(i+1));
            p3.add(cards.get(i+2));
        }
        //最后三张为底牌
        last.add(cards.get(51));
        last.add(cards.get(52));
        last.add(cards.get(53));

        System.out.println("第一个人:"+p1);
        System.out.println("第二个人:"+p2);
        System.out.println("第三个人:"+p3);
        System.out.println("底牌为:"+last);

    }
    //反转
    public static void test1(){
        List<Integer> list =new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        System.out.println(list);
        Collections.reverse(list);
        System.out.println("反转之后"+list);
    }
}
时间: 2024-09-30 10:40:24

Collection_Compare的相关文章