Find winner of local election using ArrayList


Find winner of local election using ArrayList

In this tutorial, you will learn how to find winner of local election using ArrayList.

In this tutorial, you will learn how to find winner of local election using ArrayList.

Find winner of local election using ArrayList

Here is an example that allow the user to enter the last names of five candidates in a local election and the votes received by each candidate. We have created a class Candidate which defines variables lname and vote to store the object of this class with data into ArrayList. The program output each candidate's name, the votes received by that candidate and the percentage of the total votes received by the candidate. The program will also display the winner of the election with no of votes received.


import java.util.*;
import java.text.*;
class Candidate{

public String lname;
public int vote;

public Candidate(String lname,int vote) {
this.lname = lname;;

public String getLname() {
return lname;
public int getVote(){
return vote;
class VoteComparator implements Comparator{
public int compare(Object can1, Object can2){
int v1 = ((Candidate)can1).getVote(); 
int v2 = ((Candidate)can2).getVote();

if(v1 > v2)
return 1;
else if(v1 < v2)
return -1;
return 0; 

class VotesOfCandidates
public static void main(String[] args) 
int total=0;

List<Candidate> list = new ArrayList<Candidate>();
Scanner input=new Scanner(;
for(int i=0;i<5;i++){
System.out.print("Enter Last Name: ");

System.out.print("Enter no of votes: ");
int votes=input.nextInt();
list.add(new Candidate(lname,votes));
DecimalFormat df=new DecimalFormat("##.##");
System.out.println("Total votes: "+total);
for(Candidate data: list){
int v=data.getVote();

double p=(double)v/total;
double per=p*100;
int v=0;
Collections.sort(list,new VoteComparator());
for(Candidate data: list){
String can="";
System.out.println("Highest Vote is: "+v);
for(Candidate data: list){
System.out.println(can+" won the election with "+v+" votes");


Enter Last Name: Hamelton
Enter no of votes: 2000
Enter Last Name: Gorge
Enter no of votes: 500
Enter Last Name: Messi
Enter no of votes: 2500
Enter Last Name: Lincoln
Enter no of votes: 200
Enter Last Name: Bush
Enter no of votes: 1000
Total votes: 6200
Hamelton        2000    32.26
Gorge   500     8.06
Messi   2500    40.32
Lincoln 200     3.23
Bush    1000    16.13
Highest Vote is: 2500
Messi won the election with 2500 votes