简体   繁体   中英

How can I efficiently sort an ArrayList of ArrayLists by a certain value in each ArrayList?

I have an ArrayList used to hold ArrayLists of the following form...

[sally, carp, md]
[jim, smith, ny]
[frank, franklin, ca]

I wish to sort the outer ArrayList by the third parameter (state) in the inner ArrayList. The result of sorting would be as follows...

[frank, franklin, ca]
[sally, carp, md]
[jim, smith, ny]

Is there an efficient way to do this?

I would not do this.

A better idea might be to create an object that encapsulates first name, last name, and state and have a List of those. It's easy with a Comparator once you do that.

Efficiency will be governed by the Big-Oh behavior of your sorting algorithm .

Your best bet is not to write your own sorter. Use Collections.sort() .

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

Yes, it's quite easy with Java8. Given the list:

List<List<String>> list; //let's assume it's initialized

you can sort the outer list by the third element of the inner list with:

list.sort(Comparator.comparing(l -> l.get(2)));

But @duffymo is right, you probably want to create a proper abstraction on your domain model.

Assuming you're using an arraylist of arraylists of strings:

arrayList.sort((al1, al2) -> al1[2].compareTo(al2[2]));

This creates a lambda function which accesses third elements to compare.

However, as @duffymo says, you should probably be using an arraylist of a custom class rather than an arraylist of arraylists. You'd still have to provide a sorting key for the class, though, and you'd write an effectively equivalent lambda function for your class in order to sort it.

Edit: To comment on complexity.

Also, @duffymo, I would choose a string sorting algorithm for critical code based on the class of strings I was sorting. Different collections respond differently to sorting algorithms. If you choose a non-comparison algorithm such as Burstsort , Bucket sort and Radix sort (both LSD and MSD implementations), your complexity can be linear with size by taking advantage of the structure of strings. Any default generic sorting algorithm uses comparisons (such as timsort in Python), which can be proven to take at minimum O(nlog(n)) time. Still, nlog(n) grows decently slowly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM