Home » Java » Execute arithmetic operation on concat String with Java Streams

Execute arithmetic operation on concat String with Java Streams

Posted by: admin June 14, 2018 Leave a comment


Hello guys and thank you all for helping.

I have a Stream<String> where a String can be something like “1+5*2-4” //= 8 (its ok if I calculate it from left to right)

This operation is no problem, but i try to do it now with Streams only.It means I need to use only stream operations like filter, reduce, collect…

I tried it for last 6 hours and have no idea. Its not allowed to build Lists and analyze the Elements or something in this direction. A stream operation or a many stream operations must give me an end result directly.

Someone any ideas?

My best try was

  Stream<String> numbers = myList.stream().filter(s -> 
  List<String> operands = myList.stream().filter(s -> 

   String result = numbers.reduce((a, b) -> {
   int iA = Integer.parseInt(a);
   int iB = Integer.parseInt(b);

   String operation = operands.get(0);
   return calc(iA,iB,operation);



I probably explained it badly. The end result must deliver a stream operation. In this stream operation, we may call helper methods.