In today's post we are going to solve a simple problem using List and Map in Java.
Please refer below code snippet :
▶ Problem Statement :
Mr. John have a list of players and runs made by each player. He wants to divide players into two groups - batsman and bowlers based on below condition :
- if runs made by player are less than 500 , he will be considered as bowler
else he will considered as batsman.
✅ Concepts Covered :
- Map
- List
- forEach loop
- If...Else statement
- Calling methods from main()
📑 Let's Code :)
Note* : If you are not familiar with Eclipse IDE please check my previous posts. This post will not contain basics of Eclipse or steps to empty create project.
Step 1 : We are going to use single class for this project. So let's create Main.java class.
Main.java class will contain three methods :
1. main()
2. addPlayers () - to add data
3. createBowlerAndBatsmanList() - to create two seperate lists for bowlers and batsman.
Step 2 :
1. As mentioned in the step 1 , we are going to call addPlayers() from main().
2. addPlayers() will return Map which contains name of player and total runs scored by that player.
Please refer below code snippet for the same :
Step 3 : In this step, we will write logic to create bowlers and batmans list in createBowlersAndBatsmanList().
This method accepts Map<String,Integer> as a parameter.
We will call this method from main().
1. Now, we will iterate over map using forEach loop.
2. We will check runs scored by each player,
• if runs scored are less than or equal to 500, he will be considered as bowler
• else he will be considered as batsman.
3. Accordingly we will add player to respective list.
Here we are done with the problem solution.
Hope you like this post 😃
You can reach us by entering your details in Contact Us box in the side panel💬
All the Best 👍👍👍👍
Happy Learning 😇😇😇