i have arraylist need sort need indexes of sorted items too. arraylist has many duplicate values updated , indexex duplicate. need unique indexes. there way indexes?
indices = new int[depth.size()]; arraylist<float> fstore = new arraylist(depth); collections.sort(depth); (int n=0; n<depth.size(); n++){ indices[n] = fstore.indexof(depth.get(n)); }
the problem indexof() returns index of first occurrence of element in list, or -1 if not present. if list has duplicates, then, these duplicates, you'll index of first occurrence within list.
there many ways accomplish want. 1 use sortedset , helper indexedentry class:
public class indexedentry<t extends comparable<t>> implements comparable<indexedentry<t>> { private final integer index; private final t entry; public indexedentry(integer index, t entry) { this.index = index; this.entry = entry; } public integer getindex() { return this.index; } public t getentry() { return this.entry; } @override public int compareto(indexedentry<t> other) { int byentry = this.getentry().compareto(other.getentry()); if (byentry == 0) { return this.getindex().compareto(other.getindex()); } return byentry; } @override public string tostring() { return "(" + this.entry + ", " + this.index + ")"; } } the indexedentry class wraps comparable value , index, , implements comparable first comparing value, , if value equal, compares index. means ordered list of indexedentry have elements ordered (value, index).
to use indexedentry class, iterate on collection, create indexedentry each element wrapping element , index, , sort list of indexedentry:
list<float> unordered = new arraylist<>(arrays.aslist(3.2f, 1.0f, 7.5f, 3.2f, 0.8f)); system.out.println(unordered); // [3.2, 1.0, 7.5, 3.2, 0.8] list<indexedentry<float>> ordered = new arraylist<>(); (int = 0; < unordered.size(); i++) { indexedentry<float> entry = new indexedentry<>(i, unordered.get(i)); ordered.add(entry); } collections.sort(ordered); system.out.println(ordered); // [(0.8, 4), (1.0, 1), (3.2, 0), (3.2, 3), (7.5, 2)] once sorted, ordered list contain elements along original index.
Comments
Post a Comment