java對一個int數組進行排序、去重


思路:
1、使用 HashSet 進行去重
2、將 HashSet 變為 TreeSet
3、使用 TreeSet 進行排序
4、將 Set 變為 Integer 數組
5、將 Integer 數組變為 int 數組

/**
 * @Author: DaleyZou
 * @Description:  對 candidates 數組進行排序、去重
 * @Date: Created in 10:43 2018-8-23
 * @Modified By:
 */
public class sortArray {
    public static void main(String[] args){
        /**
         思路:
         1、使用 HashSet 進行去重
         2、將 HashSet 變為 TreeSet
         3、使用 TreeSet 進行排序
         4、將 Set 變為 Integer 數組
         5、將 Integer 數組變為 int 數組
         */
        int[] candidates = {1,1,2,2,2,9,8,7,76,84,54,45}; // 初始化一個需要排序、去重的int數組
        HashSet<Integer> hashSet = new HashSet<Integer>(); // 去重
        for (int i = 0; i < candidates.length; i++){
            hashSet.add(candidates[i]);
        }
        Set<Integer> set = new TreeSet(hashSet);            // 利用TreeSet排序
        Integer[] integers = set.toArray(new Integer[]{});

        int[] result = new int[integers.length];            // 我們排序、去重后的結果數組
        for (int i = 0; i < integers.length; i++){
            result[i] = integers[i].intValue();
        }

        Arrays.stream(result).forEach(System.out::println); // 將結果數組輸出
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM