Sorting can be tricky, especially when your list is not of a primitive Java numeric type (Byte, Integer, Short, Long, Double, Float). Now, all situations will vary so this method might not be the best case. However, I’ve found it incredibly useful for simple coding challenges and university lab assignments.

To start, pick your list. For this example I’ll be using a list of `Edges` from a simple `Graph` data structure:

``// Very simple Edge classpublic class Edge {    public Vertex src;    public Vertex dst;    public double cost;        // creates an edge between two vertices    Edge(Vertex s, Vertex d, double c) {        src = s;        dst = d;        cost = c;    }}``
``// List of edgesEdge[] edges = graph.getEdges();``

Next, define the implementation of the `java.util.Comparator` interface:

``class SortByCost implements Comparator<Edge> {    public int compare(Edge a, Edge b) {        if ( a.cost < b.cost ) return -1;        else if ( a.cost == b.cost ) return 0;        else return 1;    }}``

In this example, we will be sorting the `edges` by their cost, or distance from the `src` (source) vertex to the `dst` (destination) vertex.

Finally use the standard `java.util.Arrays.sort()` method:

``Arrays.sort(edges, new SortByCost())``

And just like that, the list of` Edges` is now sorted in ascending (least to greatest) order.

If you have any questions feel free to reach out on Twitter

You can also find me on GitHub or my personal website

~ Happy Coding

— Ethan Arrowood
{"ft_lang_label":"__label__en","ft_lang_prob":0.6380385,"math_prob":0.76893157,"size":1390,"snap":"2019-51-2020-05","text_gpt3_token_len":327,"char_repetition_ratio":0.096681096,"word_repetition_ratio":0.0,"special_character_ratio":0.24604316,"punctuation_ratio":0.16666667,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98865134,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-08T01:15:55Z\",\"WARC-Record-ID\":\"<urn:uuid:e1330897-95c1-4893-b65b-2999f7b58ffa>\",\"Content-Length\":\"35873\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:5b2e8cb5-0c91-4aed-be10-05d0db36fdce>\",\"WARC-Concurrent-To\":\"<urn:uuid:0ec01817-be7b-433c-853e-d9c10b13928a>\",\"WARC-IP-Address\":\"104.25.104.32\",\"WARC-Target-URI\":\"https://www.freecodecamp.org/news/utilizing-javas-arrays-sort-for-any-list-of-objects-e3e2db61d70b/\",\"WARC-Payload-Digest\":\"sha1:CMJAWRBNLRJ62YKAUP2DG7CTNINGVL7C\",\"WARC-Block-Digest\":\"sha1:VUWSP6KLBH2OE4OEQ46IHTY7OWUKSE47\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575540503656.42_warc_CC-MAIN-20191207233943-20191208021943-00103.warc.gz\"}"}