Reference method Java 8 -
i want shuffle list. way want using sort method on list of java 8. want assign random number between 0 1 each number , based on sort list. here have , works:
list<integer> list = arrays.aslist(1,2,3,4,5); list.sort(comparing(x->new random().nextfloat()));
and works. when want use reference method that:
list.sort(comparing(random::nextfloat));
i compile time error , dont understand why. after comparator generating random number each element , sorts random number. ideas?
thank u in advance
the comparing()
method expects pass function
takes integer
, returns sort key, float
(or float
) in case.
the nextfloat()
method in class random
not take integer
(or int
) argument, method reference random::nextfloat
not work - method not have expected signature.
you make helper method:
public class example { private final random rnd = new random(); private float nextfloat(int dummy) { return rnd.nextfloat(); } public void shuffle() { list<integer> list = arrays.aslist(1,2,3,4,5); list.sort(comparing(this::nextfloat)); } }
but there's bigger problem. solution not doing think doing:
i want assign random number between 0 1 each number , based on sort list.
instead of assigning random number each number in list , sort based on that, returning different random number every time comparison method called. sort algorithm using might calling comparison method multiple times same integer. in case returning different random number each time.
this might lead strange problems, depending on sorting algorithm use. might never terminate.
implementing correctly considerably more complicated think. if real application , not practice, use collections.shuffle()
instead of implementing yourself.
here working version:
import java.util.abstractmap.simpleentry; import java.util.arraylist; import java.util.arrays; import java.util.list; import java.util.map.entry; import java.util.random; import java.util.stream.collectors; import static java.util.comparator.comparing; public final class shuffleexample { public static void main(string[] args) { list<integer> list = arrays.aslist(1, 2, 3, 4, 5); // create list of entry objects, pairs of random float // , value list random rnd = new random(); list<entry<float, integer>> entries = new arraylist<>(); (integer value : list) { entries.add(new simpleentry<>(rnd.nextfloat(), value)); } // sort list of entry objects floats entries.sort(comparing(entry::getkey)); // int values out of sorted list list<integer> shuffled = entries.stream() .map(entry::getvalue) .collect(collectors.tolist()); system.out.println(shuffled); } }
Comments
Post a Comment