Java sort integer list

sorting a List> using java Collections.sort()

I am trying to sort list using Collections.sort() . How can I sort the values inside the matchedPostions based on the StartPostion values, from lower to higher values?

you are trying to sort user defined objects. You will have to use Comparator or comparable interface. These links will help you.thejavageek.com/2013/06/17/sorting-user-defined-objects-part-1

This does not look like a list of lists of integers. This would be a list of lists: [1,198,200], [2,50,61]

5 Answers 5

You’ll need to implement a Comparator to sort custom data-structures like the one you provided.

import static java.util.Arrays.asList; List> matchedPostions = asList(asList(1, 198, 200), asList(2, 50, 61)); Collections.sort(matchedPostions, new Comparator>() < @Override public int compare(Listo1, List o2) < // Sort the lists using the starting position (second element in the list) return o1.get(1).compareTo(o2.get(1)); >>); System.out.println(matchedPostions); // [[2, 50, 61], [1, 198, 200]] 

This is the «dirty» way. The more idiomatic approach is described Duncan where you implement a Range class which properly encapsulates your data.

I would strongly recommend you create a class to hold your list values. This allows you to enjoy the benefits of type safety, including being sure you always have exactly two integer values (rather than a unknown number of items in a list). For instance:

public class Range implements Comparable  < private final int startPosition; private final int endPosition; public Range(int startPosition, int endPosition) < this.startPosition = startPosition; this.endPosition = endPosition; >@Override public int compareTo(Range o) < return startPosition - o.startPosition; >@Override public String toString() < return String.format("[%d,%d]", startPosition, endPosition); >> 

Because this class implements Comparable , you can sort with the normal Collections.sort method :

public static void main(String[] args) throws Exception < Listranges = Arrays.asList(new Range(198, 200), new Range(50, 61)); System.out.println("Unsorted"); for (Range range : ranges) < System.out.println(range); >Collections.sort(ranges); System.out.println("Sorted"); for (Range range : ranges) < System.out.println(range); >> 
Unsorted [198,200] [50,61] Sorted [50,61] [198,200] 

Источник

How to Sort a List in Java – Java List Sorting Example

Edeh Israel Chidera

Edeh Israel Chidera

How to Sort a List in Java – Java List Sorting Example

Sometimes data needs to be arranged in a specific order so it’s easier to understand, search, and process.

We call this process sorting. Sorting refers to arranging data in a specific order using certain criteria. You can sort different types of data, including numbers, strings, and objects. Java provides built-in methods for sorting, such as the Collections classes.

Sorting data in Java could be useful in an e-commerce application where a list of products needs to be displayed to the user. The products can be sorted in various ways depending on the requirements the user sets such as price, rating, brand, and so on.

For example, if the user wants to see all the products sorted by price in ascending order, the application can use a sorting algorithm to arrange the products in that order. This way, when the user views the products, they will be able to see the cheapest products first and make a purchase decision accordingly.

This article will look at various methods for sorting a list in Java.

How to Use the Collections.Sort() Method in Java

One of the most common ways to sort data in Java is to use the Collections.sort() method. It sorts a list in ascending order by default.

Here is an example of how to use the Collections.sort() method to sort a list of integers:

import java.util.Collections; import java.util.List; import java.util.ArrayList; public class Main < public static void main(String[] args) < Listnumbers = new ArrayList(); numbers.add(3); numbers.add(1); numbers.add(4); numbers.add(2); Collections.sort(numbers); System.out.println("Sorted List: " + numbers); > > 

The above code creates a list of integers, adds four numbers to it, sorts the list, and then prints the sorted list to the console.

Читайте также:  Есть ли ноль python

It uses classes from the Java standard library, including java.util.Collections , java.util.List , and java.util.ArrayList to perform the operations.

The output of the above code is shown below:

//Output Sorted List: [1, 2, 3, 4]

You can also sort a list of custom objects using the Collections.sort() method. To do this, you will need to create a comparator and pass it as an argument to the Collections.sort() method.

A comparator is an object that implements the java.util.Comparator interface. It has a single method called compare() that compares two objects and returns an integer indicating their relative order.

Here is an example of how to use a comparator to sort a list of custom objects:

import java.util.Collections; import java.util.List; import java.util.ArrayList; public class Main < public static void main(String[] args) < Listpeople = new ArrayList<>(); people.add(new Person("Alice", 25)); people.add(new Person("Bob", 30)); people.add(new Person("Charlie", 20)); Collections.sort(people, new PersonComparator()); System.out.println("Sorted List: " + people); > > class Person < private String name; private int age; public Person(String name, int age) < this.name = name; this.age = age; >public String getName() < return name; >public int getAge() < return age; >@Override public String toString() < return name + " (" + age + ")"; >> class PersonComparator implements java.util.Comparator  < @Override public int compare(Person a, Person b) < return a.getAge() - b.getAge(); >> 

The code above creates a list of ‘Person’ objects, adds several Person objects to the list, sorts the list using a custom comparator ( PersonComparator ), and then prints out the sorted list.

The Person class has two fields, name and age , and getter methods for these fields. The PersonComparator class implements the Comparator interface and overrides the compare method to sort Person objects by age.

The output of this program will be the following:

//output Sorted List: [Charlie (20), Alice (25), Bob (30)]

It’s best to use the Collections.sort() method when you have a collection of objects that need to be sorted based on one or more fields.

For example, if you have a collection of Employee objects and you want to sort them by their last name, you can use the Collections.sort() method and pass in a custom Comparator that compares the last names of the Employee objects.

How to Use the List.Sort() Method in Java

This method sorts a list in ascending order. Here’s how it works:

import java.util.Arrays; import java.util.List; public class Main < public static void main(String[] args) < Listnumbers = Arrays.asList(5, 3, 2, 4, 1); numbers.sort(null); System.out.println(numbers); // prints [1, 2, 3, 4, 5] > > 

Inside the main method above, a list of integers called «numbers» is created using the Arrays.asList method. The code then sorts this list of numbers using the default sorting method since null is passed to the sort method.

Finally, the sorted list is printed to the console using the System.out.println method, which will output «[1, 2, 3, 4, 5]».

List.sort() is useful when you have a list of elements that need to be sorted. For example, if you have a list of strings and you want to sort them in alphabetical order, you can use the List.sort() method.

List.sort() is an instance method of the List class and it sorts the elements in the order defined by their natural ordering or by a specified Icomparer implementation.

Читайте также:  Кнопка

How to Use the stream.sorted() Method in Java

In Java 8 and above, you can use the Stream API to sort a list. The Stream API provides a sorted method that you can use to sort the elements of a stream.

Here is an example of how to sort a list of integers using a stream:

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main < public static void main(String[] args) < Listnumbers = Arrays.asList(5, 3, 2, 4, 1); List sortedList = numbers.stream().sorted().collect(Collectors.toList()); System.out.println(sortedList); // prints [1, 2, 3, 4, 5] > > 

In the example above, the number list is converted to a stream using the stream() method. The sorted() method is then called on the stream to sort the elements. The collect(Collectors.toList()) method is used to collect the sorted elements back into a list. The result is a new list containing the sorted elements. The output will be «[1, 2, 3, 4, 5]».

stream.sorted() is best used when you have a stream of elements that need to be sorted. For example, if you have a stream of integers and you want to sort them in ascending order, you can use the stream.Sorted() method.

Conclusion

In this tutorial, you learned that there are several ways to sort a list in Java – the Collections.sort() method, the stream.sorted() method, and the List.sort() method. The best method to use depends on the specific requirements of the task at hand as we discussed above.

I hope this article has given you the correct information on how to sort a list in Java.

Источник

Sorting a List

Have a look at Andreas_D’s answer for explanation.In the above code all null values and +Infinity values are handled such that they move to the end.

As jarnbjo and aioobe points out a flaw in the above implementation.So I thought it’s better to restrict the implementation’s of Number.

Collections.sort(li, new Comparator() < HashSet> allowedTypes; < allowedTypes = new HashSet>(); allowedTypes.add(Integer.class); allowedTypes.add(Double.class); allowedTypes.add(Float.class); allowedTypes.add(Short.class); allowedTypes.add(Byte.class); > @Override public int compare(Number o1, Number o2) < Double d1 = (o1 == null) ? Double.POSITIVE_INFINITY : o1.doubleValue(); Double d2 = (o2 == null) ? Double.POSITIVE_INFINITY : o2.doubleValue(); if (o1 != null && o2 != null) < if (!(allowedTypes.contains(o1.getClass()) && allowedTypes.contains(o2.getClass()))) < throw new UnsupportedOperationException("Allowed Types:" + allowedTypes); >> return d1.compareTo(d2); > >); 

Using guava’s constrained list (will not allow entry of null or unsupported type to list):

List li = Constraints.constrainedList(new ArrayList(), new Constraint() < HashSet> allowedTypes; < allowedTypes = new HashSet>(); allowedTypes.add(Integer.class); allowedTypes.add(Double.class); allowedTypes.add(Float.class); allowedTypes.add(Short.class); allowedTypes.add(Byte.class); > @Override public Number checkElement(Number arg0) < if (arg0 != null) < if (allowedTypes.contains(arg0.getClass())) < return arg0; >> throw new IllegalArgumentException("Type Not Allowed"); > > ); li.add(Double.POSITIVE_INFINITY); li.add(new Integer(20)); li.add(new Double(12.2)); li.add(new Float(1.2)); li.add(Double.NEGATIVE_INFINITY); li.add(Float.NEGATIVE_INFINITY); // li.add(null); //throws exception // li.add(new BigInteger("22"); //throws exception li.add(new Integer(20)); System.out.println(li); Collections.sort(li, new Comparator() < @Override public int compare(Number o1, Number o2) < Double d1 = o1.doubleValue(); Double d2 = o2.doubleValue(); return d1.compareTo(d2); >>); System.out.println(li); 

Note that that will fail if the double values are too far apart. I would convert either to Double values and call compareTo on them, or use greater-than/less-than operators.

Here is what I think : in the compare method, check if o1 and o2 are instanceof of Comparable . If yes, then the Java code has already implemented the best possible comparison for the numerical types — use that (by calling o1.compareTo(o2) . If it does not implement Comparable , I would recommend working off BigDecimal instead of Double .

Good question +1 but bad answer, -1. Use the solution that aioobe provided — it works, this doesn’t!

As jarnbjo points out in his answer, there is no way to implement a Comparator correctly, as instances of Number may very well represent numbers larger than Double.MAX_VALUE (and that’s unfortunately as far as the Number interface allows us to «see»). An example of a Number larger than Double.MAX_VALUE is

new BigDecimal("" + Double.MAX_VALUE).multiply(BigDecimal.TEN) 

The solution below however, handles

  • Byte s, Short s, Integer s, Long s, Float s and Double s
  • Arbitrary large BigInteger s
  • Arbitrary large BigDecimal s
  • Instances of .NEGATIVE_INFINITY and .POSITIVE_INFINITY Note that these should always come before/after any BigDecimal even though the BigDecimal.doubleValue may return Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY
  • null elements
  • A mixture of all of the above, and
  • Unknown implementations of Number that also implements Comparable . (This seems to be a reasonable assumption since all Number s in the standard API implements Comparable.)
@SuppressWarnings("unchecked") class NumberComparator implements Comparator  < // Special values that are treated as larger than any other. private final static Listspecial = Arrays.asList(Double.NaN, Float.NaN, null); private final static List largest = Arrays.asList(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY); private final static List smallest = Arrays.asList(Double.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); public int compare(Number n1, Number n2) < // Handle special cases (including null) if (special.contains(n1)) return 1; if (special.contains(n2)) return -1; if (largest.contains(n1) || smallest.contains(n2)) return 1; if (largest.contains(n2) || smallest.contains(n1)) return -1; // Promote known values (Byte, Integer, Long, Float, Double and // BigInteger) to BigDecimal, as this is the most generic known type. BigDecimal bd1 = asBigDecimal(n1); BigDecimal bd2 = asBigDecimal(n2); if (bd1 != null && bd2 != null) return bd1.compareTo(bd2); // Handle arbitrary Number-comparisons if o1 and o2 are of same class // and implements Comparable. if (n1 instanceof Comparable&& n2 instanceof Comparable) try < return ((Comparable) n1).compareTo((Comparable) n2); >catch (ClassCastException cce) < >// If the longValue()s differ between the two numbers, trust these. int longCmp = ((Long) n1.longValue()).compareTo(n2.longValue()); if (longCmp != 0) return longCmp; // Pray to god that the doubleValue()s differ between the two numbers. int doubleCmp = ((Double) n1.doubleValue()).compareTo(n2.doubleValue()); if (doubleCmp != 0) return longCmp; // Die a painful death. throw new UnsupportedOperationException( "Cannot compare " + n1 + " with " + n2); > // Convert known Numbers to BigDecimal, and the argument n otherwise. private BigDecimal asBigDecimal(Number n) < if (n instanceof Byte) return new BigDecimal((Byte) n); if (n instanceof Integer) return new BigDecimal((Integer) n); if (n instanceof Short) return new BigDecimal((Short) n); if (n instanceof Long) return new BigDecimal((Long) n); if (n instanceof Float) return new BigDecimal((Float) n); if (n instanceof Double) return new BigDecimal((Double) n); if (n instanceof BigInteger) return new BigDecimal((BigInteger) n); if (n instanceof BigDecimal) return (BigDecimal) n; return null; >> 

Here is a small test program (here is an ideone.com demo):

public class Main < public static void main(String[] args) < Listli = new ArrayList(); // Add an Integer, a Double, a Float, a Short, a Byte and a Long. li.add(20); li.add((short) 17); li.add(12.2); li.add((byte) 100); li.add(0.2f); li.add(19518926L); li.add(Double.NaN); li.add(Double.NEGATIVE_INFINITY); li.add(Float.NaN); li.add(Double.POSITIVE_INFINITY); // A custom Number li.add(new BoolNumber(1)); li.add(new BoolNumber(0)); // Add two BigDecimal that are larger than Double.MAX_VALUE. BigDecimal largeDec = new BigDecimal("" + Double.MAX_VALUE); li.add(largeDec/*.multiply(BigDecimal.TEN)*/); li.add(largeDec.multiply(BigDecimal.TEN).multiply(BigDecimal.TEN)); // Add two BigInteger that are larger than Double.MAX_VALUE. BigInteger largeInt = largeDec.toBigInteger().add(BigInteger.ONE); li.add(largeInt.multiply(BigInteger.TEN)); li.add(largeInt.multiply(BigInteger.TEN).multiply(BigInteger.TEN)); // . and just for fun. li.add(null); Collections.shuffle(li); Collections.sort(li, new NumberComparator()); for (Number num : li) System.out.println(num); > static class BoolNumber extends Number < boolean b; public BoolNumber(int i) < b = i != 0; >public double doubleValue() < return b ? 1d : 0d; >public float floatValue() < return b ? 1f : 0f; >public int intValue() < return b ? 1 : 0; >public long longValue() < return b ? 1L : 0L; >public String toString() < return b ? "1" : "0"; >> > 

. which prints (I removed a few zeros):

-Infinity 0 0.2 1 12.2 17 20 100 19518926 1.7976931348623157E+308 17976931348623157000000000. 00000000010 1.797693134862315700E+310 179769313486231570000000000000. 00000100 Infinity NaN null NaN 

Источник

Оцените статью