Sorted List in java like TreeMap or SortedSet
The purpose of having a list is that they should maintain the order of the elements in which they were added. So, I believe there is no such List
implementation in which the elements are sorted as they are added.
You can use Collections.sort()
method to sort the list any time.
SortedList which allows repetition and random access of elements
You may use a TreeMap which stores the keys in sorted order and number of times that key occurs ,you can store as as values.
Now you can iterate over the Map and populate an ArrayList (filling duplicates where a key's value is greater than 0)
Overall complexity is nlogn
space complexity log n
if you extend ArrayList and find insertion point/or call collections.sort() your algorithm is O(n^2 *logn) in best case.
If your initial capacity of List isn't sufficient for all insertions it will resize(an extra O(n) operation)
Adding an element to a sorted list using inbuilt function in java
Ideally you want to use a data structure that's based on something meant for keeping items in order while you add/remove items. Those based on (balanced) binary search trees do that - examples in the Collections framework are TreeSet
and TreeMap
.
Sorting a list from the beginning
As Alencar proposes, use Collections.binarySearch(yourList, key, comparator)
to find the correct insert position. This is far faster than looking up the whole list, since binarySearch only needs log2(size of list) queries to find the correct insertion position.
So, if your insert code was
void sortedInsert(List<T> list, T value, Comparator<T> comparator) {
int pos=0;
ListIterator<T> it=list.listIterator();
while (it.hasNext() && comparator.compare(value, it.next()) < 0) pos ++;
if (pos < it.previousIndex()) it.previous();
it.add(value);
}
... and a faster version would be ...
void sortedInsert2(List<T> list, T value, Comparator<T> comparator) {
int pos = Collections.binarySearch(list, value, comparator);
if (pos < 0) {
pos = -pos -1; // returns negatives if not found; see javadoc
}
list.insert(value, pos);
}
Note that the difference may not be that great, because inserting into a non-linked list requires shifting elements up. So if the underlying list is an ArrayList
, copying, on average, half the elements one place to the right to make place for the new element results in O(n)
extra time per copy. And if the list is linked, you still need to pay that O(n)
penalty, but this time to perform the binary search -- in that case, it would probably be better to use the first version.
Note that the 1st version uses a ListIterator
just in case you decide to use linked lists. For ArrayLists
, it would be easier to use list.get(pos)
and list.add(pos, value)
, but those are a very bad idea in the context of iterating linked lists.
Is there a way to keep repeating the arraylist. like arraylist has 12, but it will continue to count while using the same list
Fist of all your problem doesn't need to iterate all the years to find sign. You can use modulus operator find equivalent year and after you can directly access sign from the array.
Scanner scan = new Scanner(System.in);
String ans = null;
System.out.print("Enter your Birth Year: ");
String[] sign = {"Monkey", "Rooster", "Dog", "Pig", "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Sheep"};
int birthYear = scan.nextInt();
do {
int mod = birthYear % 12;
ans = sign[mod];
} while (ans == null);
System.out.println("Your Zodiac Sign is: " + ans);
Related Topics
Spring - How to Use Multiple Transaction Managers in the Same Application
How to Set Order of Repositories in Maven Settings.Xml
Spring Rest Service: How to Configure to Remove Null Objects in JSON Response
Why Doesn't Java.Util.Collection Implement the New Stream Interface
Auto Resizing the Jtable Column Widths
Java How Expensive Is a Method Call
Bouncy Castle:Pemreader => Pemparser
Java String.Split() Sometimes Giving Blank Strings
What Are the Date Formats Available in Simpledateformat Class
Java Converting Int to Hex and Back Again
How to Use Argumentcaptor for Stubbing
Why Are Variables Declared with Their Interface Name in Java
What Is the Purpose of Accesstype.Field, Accesstype.Property and @Access
Parsing a Hexadecimal String to an Integer Throws a Numberformatexception