I have to take the input of some integer pairs. After that sort them and I've to do some arithmetic operation with the pair.
I used TreeMap as it allows sorting too but it fails when I have the duplicate key.
So, what collection/method should I use in my program? Please suggest.
TreeMap<Integer, Integer> h = new TreeMap<Integer, Integer>(Collections.reverseOrder());
for(int i=0; i<n; i++){
String ll[] = br.readLine().split(" ");
h.put(Integer.parseInt(ll[0]), Integer.parseInt(ll[1]));
}
Instead of using a TreeMap, you can define your own pair class, put the objects in an ArrayList and sort the elements based on the key.
class Pair{
final int first;
final int second;
.... constructor, getters
}
And then sort it using Collections.sort
Collections.sort(pairs, Pair::getFirst);
Why not implementing your own class?
Such as
class Pair implements Comparable {
int a, b;
// Implement operations you want, compareTo() method
}
The you can store these Pair objects in ArrayList<Pair> and use Collections.sort() method to sort the data way you want.
Related
PhoneBookCollection phoneBook = new PhoneBookCollection();
I have an ArrayList of PhoneBook objects. (The getCollection method returns the list)
ArrayList<PhoneBook> list = phoneBook.getCollection();
I then iterate through my ArrayList and get the PhoneBook at the i'th index and get its corresponding Telephone.
for(int i = 0; i < list.size(); i++ ){
String phone = phoneBook.getPhoneBook(i).getTelephone();
}
What I want to be able to do now is sort the getTelephone objects in ascending order.
I know that ArrayLists don't have a sort method so i'm having a bit of trouble doing this.
You can create a class that implements Comparator:
public class CustomComparator implements Comparator<PhoneBook> { // Replace PhoneBook with the appropriate
#Override
public int compare(PhoneBook t1, PhoneBook t2) {
return t1.getNumber().compareTo(t2.getNumber()); // Here compare the telephone numbers
}
}
Then do this:
Collections.sort(list, new CustomComparator());
You can use the java.util.Collections class to sort the lists. Use Collections.sort().
You can use the java.util.Collections for that.
The best will be use standart way with java.util.Collections
String class has method compareTo() and will be sorted automtically:
Collections.sort(nameOfList)
for example:
public static LinkedList<String, Double> ll = new LinkedList<String, Double>;
from your question, I think (not 100% sure) you are looking for
java.util.LinkedHashMap<K, V>
in your case, it would be LinkedHashMap<String, Double>
from java doc:
Hash table and linked list implementation of the Map interface, with
predictable iteration order. This implementation differs from HashMap
in that it maintains a doubly-linked list running through all of its
entries.
if you do want to get element by list.get(5), you could :
LinkedList<Entry<String, Double>>
so you can get Entry element by Entry entry = list.get(5), then entry.getKey() gives you the STring, and entry.getValue() gives you the Double.
Reading all your comments, I suggest you do something like this:
public class StringAndDouble {
private String str;
private double dbl;
// add constructor
// add getters, setters and other methods as needed.
// override equals() and hashCode()
}
Now you can use:
List<StringAndDouble> list = new LinkedList<>(); // or
List<StringAndDouble> list = new ArrayList<>(); // better in most cases
Now you can access your objects by index.
This answer creates a new class, to fit your needs. The class has two fields, one String, one double. This doesn't make the class two dimensional. I think you have a misunderstanding there. When there are n dimensions, you need n indexes to access an element. You were talking of accessing by index, so I assume you're looking for a one dimensional list holding the objects, that have more than one field.
Do you mean like this?
HashMap<String, Double> hm = new HashMap<String, Double>();
Since OP in a comment to #Kent says he wants to be able to get items by index...
Note that a LinkedList (and LinkedHashMap) are inefficient at that. He may prefer an ArrayList. So I would suggest that his "2D" implementation be a
ArrayList<Map.Entry<String, Double>>
which will efficiently support a get by index.
As for the normal get(String key), you'd have to do a linear search of all the entries, which would be inefficient.
So, you have a decision: which way of accessing (by a key or by an index) is more important?
You can actually use Linked Lists within eachother...
For Example:
public LinkedList<LinkedList<Integer>> twoDimLinkedList = new LinkedList<LinkedList<Integer>>();
Then:
////////////////
int value = twoDimLinkedList.get(3).get(4);
/////////////////
or (If you were planning on using it for iterative purposes):
/////////////////
for (int i = 0; i < twoDimLinkedList.size(); i++) {
LinkedList<Integer> twoDimLinkedListRow = new LinkedList<Integer>();
for (int m = 0; m < twoDimLinkedList.get(i).size(); m++) {
twoDimLinkedListRow.add(value);
}
twoDimLinkedList.add(twoDimLinkedListRow);
}
////////////////
As the title suggests, I have a list consisting of pairs of integers (int ai and int bi). I want to sort this list based on only upon int a, while preserving the pairwise relationship. I was wondering if there was an efficient way to do this with some of the standard libraries Java has. Thanks in advance!
Edit:
My exact implementation is an ArrayList<ArrayList<Integer>> in which each ArrayList<Integer> has exactly two integers (ai and bi). Sorry for any confusion.
Use the Collections sort() or Arrays sort() method which takes a Comparator and use a custom comparator which only inspects the first integer in the pair.
Something like this (roughly, depending on your exact types):
Collections.sort(myList, new Comparator<IntegerPair>() {
#Override public int compare(IntegerPair x, IntegerPair y) {
return x.first - y.first;
}
});
Since the sorting algorithms are stable (per the Javadocs) your list will be sorted per your description.
Implement http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html for your integer pairs and use sort() from http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html
I would recommend to create a class that represents integer pair. This class should implement Comparable. The use sort() to sort it.
It may be a little safer to use the already-defined Integer compare:
Collections.sort(myList, new Comparator<IntegerPair>() {
#Override public int compare(IntegerPair x, IntegerPair y) {
return Integer.compare(x.first, y.first);
}
});
I have a Map to sort as follows:
Map<String, String> map = new HashMap();
It contains the following String keys:
String key = "key1.key2.key3.key4"
It contains the following String values:
String value = "value1.value2"
where the key and value can vary by their number of dot sections from key1/value1 to key1.key2.key3.key4.key5/value1.value2.value3.value4.value5 non-homogeneously
I need to compare them according to the number of dots present in keys or in values according to the calling method type key / value :
sortMap(Map map, int byKey);
or
sortMap(Map map, int byValue);
The methods of course will return a sorted map.
Any help would be appreciated.
There is no way to impose any sort of order on HashMap.
If you want to order elements by some comparison on the keys, then use a TreeMap with some Comparator on the keys, or just use their default Comparable ordering.
If you want to order by the values, the only real option is to use a LinkedHashMap, which preserves the order that entries were put into the map, and then to sort the entries before inserting them into the map, or perhaps some non-JDK Map implementation. There are dirty hacks that make a key comparator that actually secretly compares the values, but these are dangerous and frequently lead to unpredictable behavior.
For starters, you will need to be using an instance of SortedMap. If the map doesn't implement that interface, then it has an undefined/arbitrary iteration order and you can't control it. (Generally this is the case, since a map is a way of associating values with keys; ordering is an auxiliary concern.)
So I'll assume you're using TreeMap, which is the canonical sorted map implementation. This sorts its keys according to a Comparator which you can supply in the constructor. So if you can write such a comparator that determines which is the "lower" of two arbitrary keys (spoiler alert: you can), this will be straightforward to implement.
This will, however, only work when sorting by key. I don't know if it makes much sense to sort a map by value, and I'm not aware of any straightforward way to do this. The best I can think of is to write a Comparator<Map.Entry> that sorts on values, call Map.getEntrySet and push all the entries into a list, then call Collections.sort on the list. It's not very elegant or efficient but it should get the job done if performance isn't your primary concern.
(Note also that if your keys aren't immutable, you will run into a lot of trouble, as they won't be resorted when externally changed.
You should use a TreeMap and implement a ValueComparator or make the key and value objects that implement Comparable.
Must be a duplicate here...
edit: duplicate of (to name just one) Sort a Map<Key, Value> by values (Java)
I did it by the following:
#SuppressWarnings({ "unchecked", "rawtypes" })
public static Map sortMap(Map unsortedMap) {
List list = new LinkedList(unsortedMap.entrySet());
// sort list based on comparator
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
String value1 = (String)((Map.Entry) (o1)).getValue();
String value2 = (String)((Map.Entry) (o2)).getValue();
// declare the count
int count1 = findOccurances(value1, '.');
int count2 = findOccurances(value2, '.');
// Go to thru the comparing
if(count1 > count2){
return -1;
}
if(count1 < count2){
return 1;
}
return 0;
}
});
// put the sorted list into map again
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
With the following helper method:
private static int findOccurances(String s, char chr) {
final char[] chars = s.toCharArray();
int count = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == chr) {
count++;
}
}
return count;
}
Here, I can put some switch on the comparing part with an additional int argument to change between asc/desc.
I can change between values and keys through a switch of another int argument value to get my answer.
I have a Vector of Integer ( primary key of a database table ) ; and I implemented a method which returns a String based on this primary key Integer. My problem is that I want to put these String's into a Vector and they are "sorted" in the Vector. How to achieve this String sort ?
Use the following code for sort the vector in java-me.
public Vector sort(Vector sort) {
Vector v = new Vector();
for(int count = 0; count < e.length; count++) {
String s = sort.elementAt(count).toString();
int i = 0;
for (i = 0; i < v.size(); i++) {
int c = s.compareTo((String) v.elementAt(i));
if (c < 0) {
v.insertElementAt(s, i);
break;
} else if (c == 0) {
break;
}
}
if (i >= v.size()) {
v.addElement(s);
}
}
return v;
}
You can either use a TreeSet, which will keep Strings in sorted order, or use something like this before you return them:
Collections.sort(yourVector);
Another alternative is to ask the database to ORDER BY primary key. Let the database do the work.
Your query is probably returning more than the primary keys. I'd wonder why you're dealing with things on the primitive level of a String and primary key. I'll bet you're not thinking enough in terms of objects. Where there's a primary key, other data should be following close behind. I'd encapsulate all of them together and worry about sorting those objects.
Why Vector? I'd prefer ArrayList, because it's not synchronized by default. Better performance.
You will need to implement your own comparator by implementing the Comparator interface.
Something like this should do the trick:
Collections.sort(vect, new Comparator() {
public int compare(Object a, Object b) {
return ( new Integer(((MyClass) a).getNumber()) ).compareTo( new Integer(((MyClass) b).getNumber()));
}
});
Taken from here.
Pass the vector to the static method Collections.sort(vector) not sure how you want it sorted but this method will sort according to the natural order of the objects contained in the vector, given by the compareTo method of each object.
The Collections API may be able to help you out further.
If it's Java, are you looking for
Collections.sort(vector);
?
Vector is slower than ArrayList as its a thread safe collection.
However the sort operation is not thread safe. As such to sort a vector in a thread safe manner you need to synchronize it.
synchronized(vector) {
Collections.sort(vector);
}
If you don't need the collection to be thread safe, consider using an ArrayList.
import java.util.Vector;
import java.util.Collections;
public class SortJavaVectorExample {
public static void main(String[] args) {
//create Vector object
Vector v = new Vector();
//Add elements to Vector
v.add("1");
v.add("3");
v.add("5");
v.add("2");
v.add("4");
/*
To sort a Vector object, use Collection.sort method. This is a
static method. It sorts an Vector object's elements into ascending order.
*/
Collections.sort(v);
//display elements of Vector
System.out.println("Vector elements after sorting in ascending order : ");
for(int i=0; i<v.size(); i++)
System.out.println(v.get(i));
}
}
You can either use a Collections class, which will keep Strings in sorted order, or use something like this before you return them:
if you want to sort it in ascending order use only
Collections.sort(put your....LIST/ARRAYLIST/VECTOR OBJECT HERE);
if you want to sort it in descending order use only
** Collections.sort(put your....LIST/ARRAYLIST/VECTOR OBJECT HERE);**
** Collections.reverse(put your....LIST/ARRAYLIST/VECTOR OBJECT HERE);**