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

Questions:

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 -> 
  Character.isDigit(s.charAt(0)));
  List<String> operands = myList.stream().filter(s -> 
  !Character.isDigit(s.charAt(0))).collect(Collectors.toList());



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

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


  }).get();

  System.out.println(result);

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

Answers: