java - Making a function returning the same output-type as input-type -
so let's have following generic function sorts elements in collection
(e.g. arraylist<t>
or hashset<t>
):
public static <t extends comparable> collection<t> sort(collection<t> a) { list<t> l = a.stream().sorted().collect(collectors.tolist()); return l; }
the problem when call function following code , have existing variable of type arraylist<integer>
has values:
counts = (arraylist<integer>) sort(counts);
when calling function have cast returned collection arraylist.
is there way can let sort function conversion me? if input arraylist
, output arraylist
; if input hashset
, ouput hashset
etc...
you need use generics @6ton suggests in answer, need specify supplier
sort
method, can create right collector
:
public static <t extends comparable<t>, e extends collection<t>> e sort( collection<t> a, supplier<e> factory) { return a.stream().sorted().collect(collectors.tocollection(factory)); }
then, use sort
method way:
list<float> ordered = sort(unordered, arraylist::new);
this return arraylist
, note first argument (i've called unordered
), can collection
, i.e. hashset
, treeset
, etc. similarly, can return set
, while unordered
list
or whatever collection
:
set<float> ordered = sort(unordered, linkedhashset::new);
note: others have stated, doesn't make sense sort hashset
, , same happens other collections. while specifying supplier
factory returned collection
won't produce runtime errors, doesn't mean returned collection
sorted. example:
set<float> stillunordered = sort(unordered, hashset::new);
in case, stream collected hashset
, doesn't maintain order.
Comments
Post a Comment