It can be implemented in the following ways:
1. Use List method to implement it
Method 1: Use add(0, element) and remove()
Gets the index of the specified element.
Removes the element from its current position.
Use the add(0, element) method to insert it into the first position.
Sample code:
import ; import ; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Alice"); ("Bob"); ("Charlie"); ("David"); ("Original List: " + list); // Specify the element to be ranked first String element = "Charlie"; // Get the index of the element int index = (element); if (index != -1) { // Remove elements (index); // Insert to the first position (0, element); } ("Adjusted List: " + list); } }
Running results:
Original list: [Alice, Bob, Charlie, David]
Adjusted list: [Charlie, Alice, Bob, David]
Method 2: Use ()
If you only need to swap the location of the specified element and the first element, you can use the () method.
Sample code:
import ; import ; import ; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Alice"); ("Bob"); ("Charlie"); ("David"); ("Original List: " + list); // Specify the element to be ranked first String element = "Charlie"; // Get the index of the element int index = (element); if (index != -1) { // Swap elements (list, 0, index); } ("Adjusted List: " + list); } }
Running results:
Original list: [Alice, Bob, Charlie, David]
Adjusted list: [Charlie, Bob, Alice, David]
2. Custom sorting
If the requirements are more complex, you can use Comparator to customize the sorting logic.
Sample code:
import ; import ; import ; import ; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); ("Alice"); ("Bob"); ("Charlie"); ("David"); ("Original List: " + list); // Specify the element to be ranked first final String element = "Charlie"; // Custom sorting (list, new Comparator<String>() { @Override public int compare(String o1, String o2) { if ((element)) { return -1; } else if ((element)) { return 1; } else { return 0; } } }); ("Adjusted List: " + list); } }
Running results:
Original list: [Alice, Bob, Charlie, David]
Adjusted list: [Charlie, Alice, Bob, David]
3. Things to note
If the specified element does not exist in the list, the indexOf() method will return -1, and corresponding error processing is required.
If there are multiple identical elements in the list, the indexOf() method will only move the first matching element.
When operating lists in multi-threaded environments, you need to pay attention to thread safety issues.
With the above method, you can easily move the specified element to the first position of the List.
This is the article about how Java list can rank the first element of the specified element. For more relevant Java list element sorting content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!