--Memo of the place where you got caught while studying --I could use it with Integer type, but I couldn't use Comparator with int type descending order. --The conclusion seems to be possible with boxed.
--Problems such as "Use an int type array to sort the next number in descending order and output it"
import java.util.Arrays;
import java.util.Comparator;
public class Main {
    public static void main(String[] args) throws Exception {
        
        //input
        int[] numArray = {4, 3, 2, 5, 6, 7, 3, 2, 1, 9, 7, 8, 10, 6, 4, 3, 5, 8, 9};
        Arrays.stream(numArray)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .forEach(i -> System.out.print(i + " "));
    }
}
Output result
10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 3 2 2 1 
By combining filter and distinct, you can narrow down and remove duplicates.
import java.util.Arrays;
import java.util.Comparator;
public class Main {
    public static void main(String[] args) throws Exception {
        
        //input
        int[] numArray = {4, 3, 2, 5, 6, 7, 3, 2, 1, 9, 7, 8, 10, 6, 4, 3, 5, 8, 9};
        Arrays.stream(numArray)
                .boxed()
                .distinct()
                .filter(x -> x >= 5)
                .sorted(Comparator.reverseOrder())
                .forEach(i -> System.out.print(i + " "));
    }
}
Output result
10 9 8 7 6 5 
If you rewrite the array itself, it looks like this
import java.util.Arrays;
import java.util.Comparator;
public class Main {
    public static void main(String[] args) throws Exception {
        
        //input
        int[] numArray = {4, 3, 2, 5, 6, 7, 3, 2, 1, 9, 7, 8, 10, 6, 4, 3, 5, 8, 9};
                
        numArray = Arrays.stream(numArray)
            .boxed()
            .distinct()
            .filter(x -> x >= 5)
            .sorted(Comparator.reverseOrder())
            .mapToInt(Integer::intValue)
            .toArray();
        System.out.println(Arrays.toString(numArray));
    }
}
Output result
[10, 9, 8, 7, 6, 5]
Recommended Posts