Sorting an int Array using Java Streams 使用Java Streams排序int数组

huangapple go评论59阅读模式
英文:

Sorting an int Array using Java Streams

问题

I am trying to get familiar with Java streams and similar things around that area, but unable to sort an array of type int. Here is my code, which does not sort the array at all.

class Scratch {
   public static void main(String[] args) {
       int [] arr3 = { 9,21,5,8 };
       Comparator<Integer> cc = (e1,e2) -> {
            return e1.compareTo(e2);
       };
       Arrays.stream(arr3).boxed().sorted();
       System.out.println(Arrays.toString(arr3));
   }
}
英文:

I am trying to get familiar with Java streams and similar things around that area, but unable to sort an array of type int. Here is my code, which does not sort the array at all.

class Scratch {
   public static void main(String[] args) {
       int [] arr3 = { 9,21,5,8 };
       Comparator&lt;Integer&gt; cc = (e1,e2) -&gt; {
            return e1.compareTo(e2);
       };
       Arrays.stream(arr3).boxed().sorted();
       System.out.println(Arrays.toString(arr3));
   }
}

</details>


# 答案1
**得分**: 4

I have observed that your code prints the reference of the unsorted array, whereas it should assign the sorted array to a new variable and print that instead. Furthermore, the comparator that you have defined is not used and is not required for the code's functionality.

The original array can't be changed in Java streams. Java streams work with unchangeable data and make new ones instead of modifying the original. So, if you sort with Java streams, you need to create a new sorted array. If you want to change the original array, use the usual Arrays.sort() method to sort it.

Here are both methods fixed and working, plus more:
```java
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

class Scratch {
  public static int[] UNSORTED_ARR = {9, 21, 5, 8};

  public static void main(String[] args) {
    sort1();
    sort2();
    sort3();
    sort4();
    sort5();
  }

  /**
   * Sort using comparator and streams
   */
  private static void sort1() {
    System.out.println("Sort using comparator and streams");
    Comparator<Integer> comparator = Integer::compareTo;
    var sortedStream = Arrays.stream(UNSORTED_ARR).boxed().sorted(comparator).toArray();
    System.out.println(Arrays.toString(sortedStream));
  }

  /**
   * Sort using sorted() method and streams
   */
  private static void sort2() {
    System.out.println("Sort using sorted() method and streams");
    var sortedStream = Arrays.stream(UNSORTED_ARR).sorted().toArray();
    System.out.println(Arrays.toString(sortedStream));
  }


  /**
   * Sort using sorted() method and collect list with streams
   */
  private static void sort3() {
    System.out.println("Sort using sorted() method and collect list with streams");
    List<Integer> sortedList = Arrays.stream(UNSORTED_ARR)
        .sorted()
        .boxed()
        .collect(Collectors.toList());
    System.out.println(sortedList);
  }

  /**
   * Sort using reverseOrder() method and streams
   */
  private static void sort4() {
    System.out.println("Reverse sort using reverseOrder() method and streams");
    int[] sortedArr = Arrays.stream(UNSORTED_ARR)
        .boxed()
        .sorted(Comparator.reverseOrder())
        .mapToInt(Integer::intValue)
        .toArray();
    System.out.println(Arrays.toString(sortedArr));
  }


  /**
   * Sort using Arrays.sort()
   * This modifies the original array and not using streams
   */
  private static void sort5() {
    System.out.println("Sort using Arrays.sort()");
    Arrays.sort(UNSORTED_ARR);
    System.out.println(Arrays.toString(UNSORTED_ARR));
  }
}

Output:

Sort using comparator and streams
[5, 8, 9, 21]
Sort using sorted() method and streams
[5, 8, 9, 21]
Sort using sorted() method and collect list with streams
[5, 8, 9, 21]
Reverse sort using reverseOrder() method and streams
[21, 9, 8, 5]
Sort using Arrays.sort()
[5, 8, 9, 21]
英文:

I have observed that your code prints the reference of the unsorted array, whereas it should assign the sorted array to a new variable and print that instead. Furthermore, the comparator that you have defined is not used and is not required for the code's functionality.

The original array can't be changed Java streams. Java streams work with unchangeable data and make new ones instead of modifying the original. So, if you sort with Java streams, you need to create a new sorted array. If you want to change the original array, use the usual Arrays.sort() method to sort it.

Here are both methods fixed and working, plus more:

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

class Scratch {
  public static int[] UNSORTED_ARR = {9, 21, 5, 8};

  public static void main(String[] args) {
    sort1();
    sort2();
    sort3();
    sort4();
    sort5();
  }

  /**
   * Sort using comparator and streams
   */
  private static void sort1() {
    System.out.println(&quot;Sort using comparator and streams&quot;);
    Comparator&lt;Integer&gt; comparator = Integer::compareTo;
    var sortedStream = Arrays.stream(UNSORTED_ARR).boxed().sorted(comparator).toArray();
    System.out.println(Arrays.toString(sortedStream));
  }

  /**
   * Sort using sorted() method and streams
   */
  private static void sort2() {
    System.out.println(&quot;Sort using sorted() method and streams&quot;);
    var sortedStream = Arrays.stream(UNSORTED_ARR).sorted().toArray();
    System.out.println(Arrays.toString(sortedStream));
  }


  /**
   * Sort using sorted() method and collect list with streams
   */
  private static void sort3() {
    System.out.println(&quot;Sort using sorted() method and collect list with streams&quot;);
    List&lt;Integer&gt; sortedList = Arrays.stream(UNSORTED_ARR)
        .sorted()
        .boxed()
        .collect(Collectors.toList());
    System.out.println(sortedList);
  }

  /**
   * Sort using reverseOrder() method and streams
   */
  private static void sort4() {
    System.out.println(&quot;Reverse sort using reverseOrder() method and streams&quot;);
    int[] sortedArr = Arrays.stream(UNSORTED_ARR)
        .boxed()
        .sorted(Comparator.reverseOrder())
        .mapToInt(Integer::intValue)
        .toArray();
    System.out.println(Arrays.toString(sortedArr));
  }


  /**
   * Sort using Arrays.sort()
   * This modifies the original array and not using streams
   */
  private static void sort5() {
    System.out.println(&quot;Sort using Arrays.sort()&quot;);
    Arrays.sort(UNSORTED_ARR);
    System.out.println(Arrays.toString(UNSORTED_ARR));
  }
}

Output:

Sort using comparator and streams
[5, 8, 9, 21]
Sort using sorted() method and streams
[5, 8, 9, 21]
Sort using sorted() method and collect list with streams
[5, 8, 9, 21]
Reverse sort using reverseOrder() method and streams
[21, 9, 8, 5]
Sort using Arrays.sort()
[5, 8, 9, 21]

答案2

得分: 0

每次创建一个Stream时,都会创建另一个对象。因此,您必须将排序后的流的结果分配给一个变量,并将其转换为像List这样的数据结构。

在这种情况下,不需要定义比较器,因为当调用sorted时,默认比较器是数据类型的比较器,即Integer

英文:

Every time you create a Stream, another object is created. Therefore you have to assign the result of sorted stream to a variable and transform it to a data structure like a List.

class Scratch {
   public static void main(String[] args) {
       int [] arr3 = { 9, 21, 5, 8 };
       List&lt;Integer&gt; sorted = Arrays.stream(arr3).boxed().sorted().toList();
       System.out.println(Arrays.toString(sorted));
   }
}

In this case it is not necessary to define a comparator because when you call sorted the default comparator is the comparator of the data type that is Integer.

       Comparator&lt;Integer&gt; cc = (e1,e2) -&gt; {
            return e1.compareTo(e2);
       };

huangapple
  • 本文由 发表于 2023年5月13日 07:55:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76240518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定