0

Is it possible to combine below using Java 8 streams that if there is some value for “getCount()” then keep on adding elements to same list to till size of the list is more than getCount().

List<RequestObject> li = results().map(req -> new RequestObject(req())).collect(Collectors.toList());

if(Objects.nonNull(getCount())){
    while(li.size() <= getCount()) {
        li.addAll(li);
    }
}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Abhinav
  • 1,037
  • 6
  • 20
  • 43
  • Yes correct. I edited the post. Many thanks @Andreas – Abhinav Jan 07 '20 at 13:53
  • You do know that you keep doubling the list in size, right? E.g. if the list initially has 3 values, and `getCount()` returns `6`, then you end up with a list with 12 values, i.e. each initial value will now appear 4 times each. – Andreas Jan 07 '20 at 13:58
  • Yes, I am aware of that. I need to create a payload having list's size greater than or less than based on count value. – Abhinav Jan 07 '20 at 14:06
  • adding same list again and again `li.addAll(li);`? – Ryuzaki L Jan 07 '20 at 16:02

3 Answers3

0

If you are allowed to use Java 9, it provides dropWhile(predicate) and takeWhile(predicate) for streams.

int count = 0;
List<RequestObject> li = results()
                         .map(mapping)
                         .takeWhile(obj -> {count++ <= getCount()});

EDIT: in case of Java 8 you can take a look at this answer

Steyrix
  • 2,796
  • 1
  • 9
  • 23
  • Sadly, we are still on Java 8. Thanks for your response. – Abhinav Jan 07 '20 at 14:06
  • @Abhinav and also I believe there are some 3rd party tools for that. Take a look at this article http://dubravsky.com/b/how-to-use-dropwhile-and-takewhile-in-java-8 – Steyrix Jan 07 '20 at 14:08
0

This should do it.

        List<Integer> list = IntStream.iterate(0, i -> i < getCount(), i -> i+1)
                .map(b -> getNext()).boxed()
                .collect(Collectors.toList());
        System.out.println(list);


        public static int getCount() {
           return 10;
        }
        k = 0;

        public static int getNext() {
          k += 10;
          return k;
        }
WJS
  • 36,363
  • 4
  • 24
  • 39
0

Try with create new collection based on li:

List<RequestObject> collect = IntStream.range(0, getCount())
        .mapToObj(i -> li.get(i % li.size()))
        .collect(Collectors.toList());

UPDATE

I assumed that what you want can be shown on this example (where getCount() is count):

List<String> li = new ArrayList<>(List.of("a", "b", "c"));
int count = 2;
List<String> collect = IntStream.range(0, count)
        .mapToObj(i -> li.get(i % li.size()))
        .collect(Collectors.toList());

Then you get:

[a, b]

and for example count = 10:

[a, b, c, a, b, c, a, b, c, a]
Community
  • 1
  • 1
lczapski
  • 4,026
  • 3
  • 16
  • 32