How to set the build name dynamically using the build parameters in a freestyle jenkins job

I have an active choice parameter called “Fruits” which is set to return a list in the groovy script. The list is defined as below

def FruitList=[‘fruitFilepath1’:‘fruitName1’,‘fruitFilepath2’:‘fruitName2’,‘fruitFilepath3’:‘fruitName3’]
return FruitList

Here, the first value is a path to a file and second value is the name of the fruit.
In “Build with parameters” page, as expected this parameter is displayed as dropdown with values fruitName1, fruitName2, fruitName3.
When the build is run, $Fruits gives me the file path for the selected fruit name. Which is correct.
But I also need the selected fruit name to set it as build name. How do I do this?
For example in the above list if the user selects fruitName1 then build name needs to be set to fruitName1.
I do not have the option to change the format of the above list.
Is there anyway I can do this without installing any plugins or pipeline job ?

Did you try doing this?

1. 
// Get the value of the 'Fruits' parameter
def selectedFruit = env.Fruits

// Extract the fruit name from the selectedFruit using the FruitList
def FruitList=[
  'fruitFilepath1':'fruitName1',
  'fruitFilepath2':'fruitName2',
  'fruitFilepath3':'fruitName3'
]
def selectedFruitName = FruitList.find { it.value == selectedFruit }.key

// Set the selected fruit name as an environment variable
env.SELECTED_FRUIT_NAME = selectedFruitName
  1. Use the Environment Variable for Build Name: Now you can use the environment variable SELECTED_FRUIT_NAME to set the build name. You can do this by using the “Execute shell” build step (if you’re using a Freestyle project) or in your Pipeline script:

groovyCopy code

currentBuild.displayName = env.SELECTED_FRUIT_NAME

Yes, env.variableName works only in pipeline job. This did not work for freestyle job.

I also do not want to define the list again. I want to use the one thats created first time in the groovy script.
I tried adding that also as env variable. It did not work.