this method is supposed to iterate on the TreeMaps keys. Then it should add the key to an ArrayList variable because I need to return it as one. One more thing I want to do is to sort the ArrayList.
ArrayList<String> getVehiclenames() {
ArrayList<String> vehicleList = new ArrayList<>();
for (String elem : vehicles.keySet()) {
vehicleList.add(elem);
}
Collections.sort(vehicleList);
return vehicleList;
}
I am not 100%ly sure wether thats working, but I still couldnt believe anyways that calling a collections method just sort my vehiclelist like that. I expected something like vehicleList = Collections.sort(vehicleList);.
My questions: Is this working like that? And if yes: How is that working? I tried to look it up but my knowledge is to norrow right now.
Colletoions.sort((List list) method of the collection interface sorts based on natural ordering.
The dataType of list passed in the sort method must be of type Comparable in other words, it should implement comparable interface.
In your case, you have a list of String. and String class implements the comparable interface.
So to answer your question, yes your code should work fine.
For more information, read about comparator & comparable interface http://docs.oracle.com/javase/7/docs/api/java/util/package-summary.html
From the documentation:
This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array.
Related
I have an ArrayList of some class type, in particular:
ArrayList<RowColElem<T>> myList = new ArrayList<RowColElem<T>>();
myList.add(new RowColElem(4,4,11));
myList.add(new RowColElem(1,1,11));
myList.add(new RowColElem(3,3,11));
myList.add(new RowColElem(1,0,11));
myList.add(new RowColElem(3,0,11));
The output right now is:
[(4,4,11),(1,1,11),(3,3,11),(1,0,11),(3,0,11)]
Is it possible to sort myList from ascending order with regard to both row and col? So the output would be:
[(1,0,11),(1,1,11),(3,0,11),(3,3,11),(4,4,11)]
And is it possible to sort the list inside the class where it's located rather than implementing Comparable or Comparator in **RowColElem** class?
Yes you can achieve this using Comparator methods. It is fairly neat in Java 8:
Collections.sort(myList,
Comparator.comparingInt(RowColElem::getRow).thenComparingInt(RowColElem::getCol));
This will compare using the rows and then, if they are equal, the columns. The Comparator interface has some pretty useful static and default methods - it's worth taking a good look at it.
You will have to implement the Comparable interface and your class RowColElement must provide the implementation of compareTo method, if you dont want to implement these interfaces you will have to extend ArrayList and will have to provide your own implementation. This is not a good idea, the best way will be to implement the interfaces and provide the custom comparison logic
If you want to keep your collection sorted as you insert new elements, you might want to consider using a TreeSet or another self-sorting structure instead of an ArrayList depending on your use case. These two structures will naturally keep themselves in sorted order when iterated over. Otherwise, you might have to implement your own SortedList class that does insertion sort transparently.
Either way, you'll have to implement Comparable<RowColElem<T>> on your class. It's fairly straight forward.
#Override
public int compareTo(RowColElem<T> o) {
int rowComp = Integer.compare(this.row, o.row);
if (rowComp == 0) {
return Integer.compare(this.column, o.column);
}
return rowComp;
}
I have a List of POJO. I want to sort this list based on one attribute in a custom order given in the requirement document. This attribute is of String type. There is no natural ordering possible, since the required order is not following alphabetical or any other order. Is there any way to sort this apart from doing it manually ?
What you mean by manually? You can always do
Collections.sort(yourList, new Comparator<String>(){
//implement your compare method in the way your doc describes it
});
yes. Write your own Comparator to custom sort your elements and then pass it to Collections.sort()
You need to implement Comparable interface and override the compareTo() method.
For example: Suppose if you want to sort a student list based on student ID then you can do it as:
#Override
public int compareTo(Student stu) {
return (this.id - stu.id);
}
I used a comparator along with a defined sort order (This was something I looked for). This will give me the list sorted in the order I wanted.
Arrays.asList returns a typed List. But List is an interface so how can it be instantiated? If try and instantiated a typed List I get an error saying it is not possible.
Edit
Nevermind I see what's going on, just got confused by the docs for a moment.
It's an Arrays.ArrayList which shouldn't be confused with java.util.ArrayList. It is a wrapper for the array which means any changes you make, alter the original array, and you can't add or remove entries. Often it is used in combination with ArrayList like
List<String> words = new ArrayList<>(Arrays.asList("Hello", "There", "World"));
A List can't be instantiated, sure. But you can instantiate a class which implements List -- for example, an ArrayList or LinkedList, etc. These classes really are Lists. The point of returning a List (the interface type) is that the method can return any object which implements the List interface, and you shouldn't worry about exactly which concrete type it is.
from class Arrays
public static transient List asList(Object aobj[])
{
return new ArrayList(aobj);
}
so when you execute Arrays.asList(...) you will take ArrayList which implements List. nobody will know that, except this one itself.
1 example
String[] array = new String[] {"one","two","three"};
List list = Arrays.asList(array);
I start learning the Java generic collection using Deitel Harvey book - but I am facing a difficulty understanding the three line of codes below - Do all of them perform the same operation on by intializing and adding the relevant values of array ( colors ) to the LinkList variable (list1). How does the second method and third method works - I am having a bit difficulty understanding how Arrays can viewed as a list.. As I know arrays are not dynamic data structure, they have fixed sized length, adding/ removing elements on array can not be done on running time comparing to Lists in general.
String[] colors = { "black", "white", "blue", "cyan" };
List< String > list1 = new LinkedList< String >();
// method 1 of initalizing and adding elments to the list
for (String color : colors)
list1.add(color);
// method 2 of initializing and adding elements to the list
List< String > list1 = new LinkedList< String > (Arrays.asList(colors));
// method 3 of initializing and adding elements to the list
List< String > list1 = Arrays.asList(colors);
Please help me understand my queries above, don't judge me as I am still new to this.
Thank you, Sinan
Actually knowledge of generics is not necessary for answering this question.
As you correctly identifier arrays are static in the sense that you can't add elements to them or remove them.
Lists, however, usually allow those operations.
The List returned by Arrays.asList() does have the add/remove methods (otherwise it would not be a valid List). However actually calling those methods will throw an UnsupportedOperationException exactly because you can't actually add elements to an array (for which this List is simply a view/wrapper).
Operations that don't structurally modify the list (i.e. that don't change the number of elements in the list) are entirely possible: set(int, E) works just fine on the List returned by Arrays.asList().
Arrays.asList returns a fixed-size list backed by the specified array.
It is actually a bridge between Array and Collection framework. But returned list write through to the array.
Only your first method does anything to the LinkedList you have initially assigned into list1. The other two assign a new, unrelated list to it. The third option assigns something that isn't a LinkedList, but a special implementation of the List interface backed by your String array. In the third case you won't be able to add/remove elements from the list, but you can iterate over it and update existing slots. Basically, it does what a plain array does, just through the List interface.
Arrays.asList creates a List from an Array. Arrays in general can't be viewed as lists in Java. They can only be wrapped in a list.
So method 2 is used to have a specific list implementation LinkedList in this case.
to Method 2, just check the Api here:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList(java.util.Collection)
For sure, Lists implement the Collections Interface so this Constructor will work here.
to Method 3, just check out the Api here: http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)
Every time you are interested in implementation you can look into certain method. For example, by press Ctrl+left mouse button onto method or class.
// method 2 of initializing and adding elements to the list
List<String> list1 = new LinkedList<String> (Arrays.asList(colors));
This code leads to:
List<String> list1 = new LinkedList<String> (new ArrayList<String>(colors));
In constructor of ArrayList:
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
the actual array is copied to encapsulated private array field(link is copied).
Then in constructor of LinkedList:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
Every element of passed collection is added to the LinkedList.
if you see the link below
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList%28java.util.Collection%29
you will see the constructor of linked list class which is accepting a collection object as parameter.
Any in your post, the 2nd and 3 rd lines are passing an object of collection class(i.e Arrays.asList is finally giving a List which is a sub class of collection).
So both 2nd and 3rd lines fairly valid implementations.
More over you can observe one more good coding practice in all the 3 lines.
That is
writing code to interceptors than to classes
. (referring
LinkedList
instance with
List
interface)
Always try to refer your classes with interceptors which is a good practice
I have a list of objects I need to sort according to properties of one of their fields. I've heard that SortedMap and Comparators are the best way to do this.
Do I implement Comparable with the class I'm sorting, or do I create a new class?
How do I instantiate the SortedMap and pass in the Comparator?
How does the sorting work? Will it automatically sort everything as new objects are inserted?
EDIT:
This code is giving me an error:
private TreeMap<Ktr> collection = new TreeMap<Ktr>();
(Ktr implements Comparator<Ktr>). Eclipse says it is expecting something like TreeMap<K, V>, so the number of parameters I'm supplying is incorrect.
The simpler way is to implement Comparable with your existing objects, although you could instead create a Comparator and pass it to the SortedMap.
Note that Comparable and Comparator are two different things; a class implementing Comparable compares this to another object, while a class implementing Comparator compares two other objects.
If you implement Comparable, you don't need to pass anything special into the constructor. Just call new TreeMap<MyObject>(). (Edit: Except that of course Maps need two generic parameters, not one. Silly me!)
If you instead create another class implementing Comparator, pass an instance of that class into the constructor.
Yes, according to the TreeMap Javadocs.
Edit: On re-reading the question, none of this makes sense. If you already have a list, the sensible thing to do is implement Comparable and then call Collections.sort on it. No maps are necessary.
A little code:
public class MyObject implements Comparable<MyObject> {
// ... your existing code here ...
#Override
public int compareTo(MyObject other) {
// do smart things here
}
}
// Elsewhere:
List<MyObject> list = ...;
Collections.sort(list);
As with the SortedMap, you could instead create a Comparator<MyObject> and pass it to Collections.sort(List, Comparator).
1.
That depends on the situation. Let's say the object A should sort before the object B in your set. If it generally makes sense to consider A less than B, then implementing Comparable would make sense. If the order only makes sense in the context in which you use the set, then you should probably create a Comparator.
2.
new TreeMap(new MyComparator());
Or without creating a MyComparator class:
new TreeMap(new Comparator<MyClass>() {
int compare(MyClass o1, MyClass o2) { ... }
});
3. Yes.
Since you have a list and get an error because you have one argument on the map I suppose you want a sorted set:
SortedSet<Ktr> set = new TreeSet<Ktr>(comparator);
This will keep the set sorted, i.e. an iterator will return the elements in their sort order. There are also methods specific to SortedSet which you might want to use. If you also want to go backwards you can use NavigableSet.
My answer assumes you are using the TreeMap implementation of SortedMap.
1.) If using TreeMap, you have a choice. You can either implement Comparable directly on your class or pass a separate Comparator to the constructor.
2.) Example:
Comparator<A> cmp = new MyComparator();
Map<A,B> map = new TreeMap<A,B>(myComparator);
3.) Yes that's correct. Internally TreeMap uses a red-black tree to store elements in order as they are inserted; the time cost of performing an insert (or retrieval) is O(log N).
You make a Comparator<ClassYouWantToSort>. Then the Comparator compares the field that you want to sort on.
When you create the TreeMap, you create a TreeMap<ClassYouWantToSort>, and you pass in the Comparator as an argument. Then, as you insert objects of type ClassYouWantToSort, the TreeMap uses your Comparator to sort them properly.
EDIT: As Adamski notes, you can also make ClassYouWantToSort itself Comparable. The advantage is that you have fewer classes to deal with, the code is simpler, and ClassYouWantToSort gets a convenient default ordering. The disadvantage is that ClassYouWantToSort may not have a single obvious ordering, and so you'll have to implement Comparables for other situations anyway. You also may not be able to change ClassYouWantToSort.
EDIT2: If you only have a bunch of objects that you're throwing into the collection, and it's not a Map (i.e. it's not a mapping from one set of objects to another) then you want a TreeSet, not a TreeMap.