I need a method to order a Map of generic object by a generic attribute of the object. I tried the code below, similar to other example I found on StackOverFlow, but I didn't find any example with a generic attribute. I'm not expert of lamda, so for me it is hard to understand clearly some logics.
I get error on compareTo; Ntebeans says me:
"cannot find symbol symbol: method compareTo(CAP#1) location: class Object where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of ?"
Example:
- I have a object 'car' with attribute 'name'
- I have an Hashmap<Integer,car>, containing items: key 1, object with name=Ford --- key 2, object with name=Audi --- key 3, object with name=Fiat
- The first element of the map has key 1, the second has key 2, the third has key 3
- I would like to have in output an Arraylist where: - The first element is object 'Audi', the second is object 'Fiat', the third is object 'Ford', so to have the 3 names sorted.
In order to invoke this method I would use for example:
ArrayList<Car> SORTED_Cars = get_ListOfObject_SortedByAttribute(myHashMap, car -> car.getName() );
I should get an ArrayList of object 'car' ordered by attribute 'name'.
The final task is to have a method that I'll use with Map of different Objects, then with different attributes.
Note that I use this checking condition
if (MyMap_Arg!=null && MyMap_Arg.size()>0 && MyMap_Arg.values()!=null)
because I prefer get null when the ordering is not possible or the map is empty.
How should be the code below to work?
private static <T> List<T> get_ListOfObject_SortedByAttribute(final Map<?, T> MyMap_Arg, final Function<T, ?> MY_AttributeValueExtractor__Arg ) {
List<T> result = null;
try {
if (MyMap_Arg!=null && MyMap_Arg.size()>0 && MyMap_Arg.values()!=null){
if (MY_AttributeValueExtractor__Arg!=null ) {
//_____________________________________________________
//Crea una lista di oggetti che hanno MY_AttributeValueExtractor_1_Arg!=null; altrimenti applicando '.compare' darebbe exception
List<T> MY_LIST__SenzaNull = MyMap_Arg.values().stream().filter( o -> MY_AttributeValueExtractor__Arg.apply(o)!=null ).collect(Collectors.toList());
//_____________________________________________________
//TEST ********* Ordina la lista di oggetti alfabeticamente in base a MY_AttributeValueExtractor_1_Arg
result = MY_LIST__SenzaNull.stream().sorted(
(o1, o2)-> MY_AttributeValueExtractor__Arg.apply(o1).
compareTo( MY_AttributeValueExtractor__Arg.apply(o2) )
).
collect(Collectors.toList());
//_____________________________________________________
}
}
} catch (Exception ex) {
result=null;
}
return result;
}