0
List<Mt4Strategy> openStrategies = ...

OrderType sample = openStrategies.get(0).calculate().getOrderType();
boolean success = true;
for (int i = 1; i < openStrategies.size(); i++) {
    Mt4Action calculate = openStrategies.get(i).calculate();
    if (calculate.getOrderType() != sample) {
        success = false;
        break;
    }
}

OrderType is an enum.

I don't know what the first element contains and as a result am forced to make openStrategies.get(0).... I want to get rid of this get(0), but how?

I tried to use lambda like this:

OrderType sample = openStrategies.get(0).calculate().getOrderType();
boolean success = IntStream.range(1, openStrategies.size()).mapToObj(i ->
        openStrategies.get(i).calculate()).noneMatch(calculate -> 
        calculate.getOrderType() != sample);

It's a good start but does not resolve my get(0).

Can using a lambda get rid of it? How I can write this to check success without get(0)? Lambda solution in priority something similar to last case .noneMatch.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Pavel
  • 2,005
  • 5
  • 36
  • 68
  • What is the code suppesed to do? Test if all `OrderType`s are distinct? – Alex R Nov 09 '19 at 02:04
  • yes OrderType never equals null always have a distinct value – Pavel Nov 09 '19 at 02:14
  • Your current code compares the rest of the element with the first element and finds if any of them is not the same as it. Now your converted code already does that, are you ending up asking a duplicate of [Java: Get first item from a collection](https://stackoverflow.com/questions/1671378/java-get-first-item-f?rom-a-collection) – Naman Nov 09 '19 at 04:23

1 Answers1

2

You apparently want to determine whether all the input list elements have the same order type. A stream ought to make this pretty simple. For example,

boolean success = openStrategies.stream()
    .map(s -> s.calculate().getOrderType())
    .distinct()
    .limit(2)
    .count() == 1;

Note here the distinctness comparisons are done with equals rather than ==. If you really need ==, it's more difficult.

This checks for exactly one value in the list. If the input can be empty and you want the result to be true in that case, change == 1 to <= 1.

The limit(2) isn't needed for correctness but allows the search to stop as soon as a second distinct value is found, so it's more efficient.

There are other ways to do this.

Responding to comment

There are various hacky ways you could get the common value without calling .get(0), but none that would be clearer (at least that I can think of). It's silly to code things in oddball ways just to avoid a call you don't like the looks of.

Gene
  • 46,253
  • 4
  • 58
  • 96
  • thank you for the answer, can you please add case how I can get the value of order type if it possible? I should return the order type actually. – Pavel Nov 09 '19 at 11:29