logo
down
shadow

Java How to sort an array of signed integers in descending order ignoring the signs?


Java How to sort an array of signed integers in descending order ignoring the signs?

By : ziyounandiao
Date : November 20 2020, 11:01 PM
I hope this helps you . The title is self-explanatory. E.g , Short version :
code :
Integer[] ary = { 2, 1, 0, -2, -5 };

Arrays.sort(ary, (Integer i1, Integer i2) -> Math.abs(i2) - Math.abs(i1));
System.out.println(Arrays.toString(ary));
int[] ary = { 2, 1, 0, -2, -5 };

List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < ary.length; index++) { 
  intList.add(ary[index]);
} 

intList.sort((Integer i1, Integer i2) -> Math.abs(i2) - Math.abs(i1));

System.out.println(intList);
[-5, 2, -2, 1, 0]


Share : facebook icon twitter icon
Need help in understanding this specific descending order selectiion sort of integers

Need help in understanding this specific descending order selectiion sort of integers


By : smstms
Date : March 29 2020, 07:55 AM
this one helps. First of all I would highly suggest to get your code more formatted. In Eclipse it is done by pressing [Ctrl]+[Shift]+[F].
By doing that, your code should look like that (I did some improvements which I will explain then).
code :
import java.util.Scanner;

public class Selectionsort_descending {
public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter any number");
    int n = sc.nextInt();
    int a[] = new int[n];

    for (int i = 0; i < n ; i++) {
        System.out.println("Enter number");
        a[i] = sc.nextInt();
    }

    for (int j = 0; j < n ; j++) {
        for (int k = j; k < n; k++) {
            if (a[j] < a[k]) {
                int m = a[j];
                a[j] = a[k];
                a[k] = m;
            }
        }
    }

    for (int i = 0; i < n ; i++) {
        System.out.print(a[i] + " ");
    }

    sc.close();
}
}
How to sort integer array in ascending and descending order using lambda only in java

How to sort integer array in ascending and descending order using lambda only in java


By : Martin Gordon
Date : March 29 2020, 07:55 AM
Hope that helps , You could sort the input of type Integer[] as :
code :
Integer[] arr2 = new Integer[] {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());
int[] arr2 = new int[]{54, 432, 53, 21, 43};
int[] sortedArray = Arrays.stream(arr2)
        .boxed()
        .sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
        .mapToInt(Integer::intValue)
        .toArray();
int[] sortedArray = Arrays.stream(arr2)
        .map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
        .toArray();
int[] arr2 = new int[]{54, 432, 53, 21, 43};
Arrays.sort(arr2);
Partially sort an array in descending order using Java Stream API

Partially sort an array in descending order using Java Stream API


By : user3161077
Date : March 29 2020, 07:55 AM
To fix this issue I need to know how to partially sort an array of primitive unique integers in descending order using Stream API. For example, if there is an array like {1,2,3,4,5}, I want to get {5,4,3, 1,2} - 3 biggest elements first and then the rest. Is it even possible using streams? I checked the docs - there are two methods skip and limit but they change the stream content and work from the beginning of the array. , Here's an approach using streams.
code :
int[] sortPartially(int[] inputArray, int limit) {
    Map<Integer, Long> maxValues = IntStream.of(inputArray)
                                            .boxed()
                                            .sorted(Comparator.reverseOrder())
                                            .limit(limit)
                                            .collect(Collectors.groupingBy(x -> x, LinkedHashMap::new, Collectors.counting()));

    IntStream head = maxValues.entrySet()
                              .stream()
                              .flatMapToInt(e -> IntStream.iterate(e.getKey(), i -> i)
                                                          .limit(e.getValue().intValue()));

    IntStream tail = IntStream.of(inputArray)
                              .filter(x -> {
        Long remainingDuplication = maxValues.computeIfPresent(x, (y, count) -> count - 1);
        return remainingDuplication == null || remainingDuplication < 0;
    });

    return IntStream.concat(head, tail).toArray();
}
Collection<Integer> sortPartially(int[] inputArray, int sortedPartLength) {
    Queue<Integer> pq = new PriorityQueue<>(sortedPartLength);

    Deque<Integer> result = IntStream.of(inputArray).boxed().map(x -> {
        pq.add(x);
        return pq.size() > sortedPartLength ? pq.poll() : null;
    }).filter(Objects::nonNull).collect(Collectors.toCollection(ArrayDeque::new));

    Stream.generate(pq::remove).limit(sortedPartLength).forEach(result::addFirst);

    return result;
}
JAVA: Me need sort a series in an array in descending order

JAVA: Me need sort a series in an array in descending order


By : user3442789
Date : March 29 2020, 07:55 AM
To fix this issue You can sort the array as you already do, and then iterate the array and swap first with last, second with last-1, etc. Like in the following code snap:
code :
 Arrays.sort(twoDimArray[twoDimArray.length - 1]);
 //Swap 
 for (int i = 0, j = twoDimArray[twoDimArray.length - 1].length - 1, tmp; i < j; i++, j--) {
     tmp = twoDimArray[twoDimArray.length - 1][i];
     twoDimArray[twoDimArray.length - 1][i] = twoDimArray[twoDimArray.length - 1][j];
     twoDimArray[twoDimArray.length - 1][j] = tmp;
  }
[7, 3, -6]
 int [] a = twoDimArray[twoDimArray.length - 1];
 Arrays.sort(a);
 //Swap
 for (int i = 0, j = a.length - 1, tmp; i < j; i++, j--) {
    tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
  }
  System.out.println(Arrays.toString(twoDimArray[twoDimArray.length - 1]));
How to sort an array of integers in descending order of the first digit?

How to sort an array of integers in descending order of the first digit?


By : Michele Contesi
Date : March 29 2020, 07:55 AM
wish helps you The ordering you require is a lexicographical descending order.
A lexicographical descending order is the order you'll get if you treat the numbers of the input list as Strings and sort them in descending order. If all the integers had the same number of digits, the lexicographical order would be the same as natural ordering of integers.
Related Posts Related Posts :
  • ExecutorService and OutOfMemoryError: unable to create new native thread while using Executor
  • Java Security Manager completely disable reflection
  • Placement of Thread Content. How do you know what goes inside of the thread, and what doesn't?
  • can not search for txt files android 6.0
  • Monitor program using semaphore does not work as expected in java
  • A way to define / implement failover ldap servers in java code
  • How to save embedded object in POST call using Spring Data Rest
  • Methods in test in parallel way
  • What would be the best way to implement to check if the Post has been liked by the User using JPA and MySQL?
  • GCM unregister causing the application to crash
  • Test configuration annotations in separate annotation
  • How to catch third party console log using log4j
  • Spring Boot: Conditional on database type
  • Java: Loading data from a file located under project folder fails
  • Epson epos sdk receipt alignment issue
  • Java Comparable: helper methods for isLessThan, isGreaterThan, isEqualTo
  • How to find the native method from the JVM source code?
  • Insert datetime string from java in MySQL
  • Regex look ahead to seperate string into tokens
  • How the java de-compiler get to know the variable or object names?
  • Java generics "capture of ?"
  • Specify the default value of the JSONP callback in spring using jackson?
  • Digital Signature created in C# doesn't match in Java verification
  • How to push down project, filter, aggregation to TableScan in Calcite
  • Java/SQL find duplicates
  • Getting a null error trying to add objects into an arraylist (simple piece of code)
  • JDBC query returning zero when using simple arithmetic operations and alias even though the data in table is not zero
  • incompatible type while adding value to Map
  • Openshift Build Failure - Failed to read artifact descriptor
  • updating neo4j database using java program
  • how to save an image to disk and retrive it with java/jsp
  • How to verify kerberos token?
  • String to byte array conversion varies from windows and ubuntu
  • Custom MavenResourcesFiltering hard to implement?
  • TestNG XML file failed to invoke/create the XSSFWorkbook
  • BigDecimal issue with long and lat
  • I am new to JavaFX. I want help on how to make a TreeView node Draggable and Droppable
  • Microservices and Messaging: Message Content
  • How to move an email service into a thread?
  • Reading a .csv file faster than reading same file compressed as .gz
  • How to change the json response fields to user defined fields in java?
  • Retrofit: Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for CustomClass
  • Basic Authentication failed in Windows server 2012 Using Java
  • Avoid Transaction rollback in Spring
  • Transition between right - up, left - down, down - left etc. (JAVA game LWJGL keylistener)
  • How to setup a common classpath for all dependencies inside a maven project?
  • How is Mockito.mock better that using new while writing Junit tests?
  • In apache http client, how to keep the Content-Type in a StringBody as empty or null?
  • SQuirreL Configure: could not initial class org.apache.phoenix.jdbc.PhoenixDriver
  • ResponseEntity decode UTF-8
  • Time difference gives wrong value
  • How to read in and split a string of numbers separated by whitespace and forward slash
  • InvocationTargetException in javafx
  • method reference vs lambda expression
  • Scaling issue in BigDecimal(java) for exponential notation
  • What is causing my app to crash in this program? - Android Studio
  • My method returning an Optional cannot be used in a functional-like way
  • Dangling meta character '*' near index 6
  • How to parse a string in java to get only some parts of it
  • How to replace special character using regex in Mule Dataweave transformation?
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com