Unique maximum element of Scala list

I wish to do a max function using apache flink with Scala that returns the maximum element, if it is unique, and -1 otherwise. For better understanding there is an example below:

2 is the return of the function for list[1, 2, 1].

-1 is the return of the function for list[3, 3, 1] due to the max result it will be three, but is not an unique appearance in the list of this max value.

I thougth that i could do by putting all elements on a seq, but this won't work after with flink, so i tried to do using reduce, but i got no success :/

Can anybody help?

2 answers

  • answered 2018-11-07 22:27 Knows Not Much

    Use Flink API to fold the list. Start with a tuple of (0, 0). the first is the max number so far and the second is the number of times you found that number.

    When you find a number x which is greater than _1 of the tuple you creates a tuple (x, 0). If you find a number which is less than x then ignore. if you find a number which is equal to x then increment the _2 of the tuple.

    At the end of the fold you will have a tuple which is (x, y) where x is the maximum number and y is the number of times you found that number.

    How a simple if condition will help you return the x or a -1.

    Edit: Flink has deprecated the fold function. Use the AggregateFunction for traversing the list.


  • answered 2018-11-07 22:30 Rajkumar Natarajan

    This should solve your problem

     val x: List[Int] = ???
     val grouped: Map[Int, List[Int]] = x.groupBy(identity)
     val uniqueElements:List[Int] = grouped.filter( _._2.size == 1 ).map(_._1).toList
     val maxVal = if(uniqueElements.isEmpty ) -1 else uniqueElements.max