-2

I have a String named headline, and it should be a random combination of three to five words from the following list: up, down, rise, fall, good, bad, success, failure, high, low.

I created a list such as:

List list= new ArrayList();
list.add("up");
list.add("down");
list.add("fail");
list.add("success");
list.add("good");
list.add("bad");
list.add("upper");
list.add("uber");

How would I get a random combination of three to five words from this list?

SiKing
  • 10,003
  • 10
  • 39
  • 90
maede
  • 1
  • 2

1 Answers1

0

It is possible to use stream of random int indexes in the input list (then duplicate values are possible) with the help of Random::ints:

Random random = ThreadLocalRandom.current();

List<String> combination = random
    .ints(3 + random.nextInt(3), 0, list.size()) // IntStream random indexes
    .mapToObj(list::get)
    .collect(Collectors.toList());

Example:

[success, uber, up, uber, fail]

Or distinct values may be selected with randomized Stream::limit:

List<String> combination = random
    .ints(0, list.size()) // IntStream random indexes
    .distinct()
    .limit(3 + random.nextInt(3))
    .mapToObj(list::get)
    .collect(Collectors.toList());

Example:

[up, down, bad, fail]
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • now how to check If more than 50% of words in the combination are positive ("up", "rise", "good"...) or not? @Alex Rudenko – maede Aug 27 '21 at 23:05
  • Define a set of positive words, and count how many of the random combination is in this set: `Set positive = Set.of("up", "good", "success"); double percent = 100.0 * combination.stream().filter(positive::contains).count() / combination.size();` Also, it may be better to use enum instead of plain String and provide `positive` as a field of this enum. – Nowhere Man Aug 28 '21 at 05:11
  • Thanks a lot It worked :) You are my hero . @Alex Rudenko – maede Aug 30 '21 at 09:47