Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java list stream, get all elements or just one?

I have a method that returns an Arraylist of elements. Sometimes I need the whole list, and sometimes just to check if the resulting list is not empty (just the bool).

Since that method does some heavy tasks to check if something should be added to the result list, is there a way to break in the method in case it adds one element to list??

I would like to use the same method, but sometimes break if one element is added to the list, and sometimes let it do all work (and add everything else).

I can pass some boolean flags that will indicate if the method should break when there is a first element added event, but I wonder if there is a more elegant solution (with stream or something...).

I added pseudo code as an example. This method is recursive, and I would like to (optionally) avoid additional recursive calls if I add an element in the first iteration:

List<String> getData(argument) {
  List<String> elements = new ArrayList<>;
  ... // do some heavy stuff that produces flag 'shouldAddElement'

  if (shouldAddElement) {
    elements.add('a');
  }

  if (someCondition) {
    elements.addAll(getData(argument));
  }

  return elements;
}
like image 561
user3921420 Avatar asked Mar 29 '26 00:03

user3921420


1 Answers

You can pass a predicate shouldContinue (or even equivalently shouldStop) to the method and based on the evaluation of the predicate you can decide to continue/stop.

However, adding this parameter to a public method may not seem that appropriate, so you could create two methods - one that stops after adding one element, and one that keeps continuing (since anyway the caller needs to decide whether to stop after one element or to keep going(if you decide to pass a flag) - so, you may very well have two methods IMO).

List<String> getOneElementData(argument) {
    return getDataInternal(argument, elements -> elements.size < 1);
}

//You can even extend the above to take the desired final list size as a parameter
// and have the predicate as elements -> elements.size < desiredSize

List<String> getData(argument) {
      return getDataInternal(argument, elements -> true); //Always keep going
}

private List<String> getDataInternal(argument, Predicate<List<String>> shouldContinue) {
  List<String> elements = new ArrayList<>;
  ... // do some heavy stuff that produces flag 'shouldAddElement'

  if (shouldAddElement) {
    elements.add('a');
  }

  if (someCondition && shouldContinue.test(elements)) {
    elements.addAll(getData(argument));
  }

  return elements;
}
like image 61
user7 Avatar answered Apr 01 '26 10:04

user7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!