Does Java have a built-in way to add an item to an alphabetical list?

Is there a method already provided in the Java 5 library to add an element in alphabetical order List?

In other words, let's say I have one List<String>with three elements {"apple","cat","tree"}, and I want to add a banana String, keeping it Listin alphabetical order; is there an easy way to just add it in List, so Listnow it has four elements {"apple","banana","cat","tree"}?
+3
source share
8 answers

You can use PriorityQueue. They are sorted by the comparator of the objects they store. Stringsby default, they are sorted according to the ASCII values ​​of the first different character, which will give the desired results (as long as the capitalization of all words is the same.)

Quick example:

PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("banana");
pq.add("apple");
pq.add("orange");
pq.poll(); // Returns "apple"
pq.poll(); // Returns "banana"
pq.poll(); // Returns "orange"

Note that Big-O runtime add()is both poll()equal and equal O(logn).

Edit: PriorityQueuebest if you want to remove items in order, but you need TreeSetto repeat through the collection in order.

+7
source

, , , Collections.sort() . String . Collections.sort() , , . , , T Comparable.

EDIT: , , . , List, n- .

+1

TreeSet. , String.compareTo() .

, .

+1

, , ,

  • ( ) ,
  • , , i, list.add(i, element)

.

String element = "banana";
List<String> list = new ArrayList<String>();
int i = Collections.binarySearch(list, element);
if (i < 0) {
    list.add(-(i+1), element);
} else {
    list.add(i, element);
}

. Collections.binarySearch() , .

+1

List - . , , , , TreeSet. , .

+1

, , , , , . . , , , List .

0

The function addToSortedI wrote is not provided by default in Java, but is still very simple. The function Collections.binarySearchreturns either a value >= 0if an element is found, or a value < 0if a value is not found. In the latter case, it returns the position of the insert (encoded to some extent so that it is always negative).

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BinSort {

  private static void addToSorted(List<String> list, String element) {
    int index = Collections.binarySearch(list, element);
    if (index < 0)
      list.add(-(index + 1), element);
  }

  public static void main(String[] args) {
    List<String> words = new ArrayList<String>();
    words.add("apple");
    words.add("cat");
    words.add("tree");
    addToSorted(words, "banana");
    System.out.println(words);
  }
}
0
source

Source: https://habr.com/ru/post/1753756/


All Articles