Mohit Gupta
Mohit Gupta

Reputation: 1

Approach to find Average by X from a file.?

Let's say I have a CSV file.

For Example:

City,Year,Income Delhi,2001,12345 Mumbai,2001,43211 Hyderabad,2001,54322 Delhi,2002,76543 Mumbai,2002,43211 Hyderabad,2002,54322 Bangalore,2001,43211 Bangalore,2001,54322

I want to find the average by City.

Output:

Delhi - 876543 Mumbai - 86543 Hyderabad - 356785 Bangalore - 64352

The approach which I used is by using multiple Map. But I guess it will be taking more space.

Can anyone suggest me a better approach to solve this?

Thanks

Upvotes: 0

Views: 52

Answers (2)

TongChen
TongChen

Reputation: 1430

First,we define a DTO to express the data in CSV file,one line one DTO

public class CityIncome {
        private String city;
        private String year;
        private int income;

        public CityIncome(String city, String year, int income) {
            this.city = city;
            this.year = year;
            this.income = income;
        }
    }

Second,read all data in CSV file into a List<CityIncome>

Third,use Java Stream API to group and reduce the result,may like this:

Map<String, Double> groupResult = cityIncomes.stream()
                .collect(Collectors.groupingBy(CityIncome::getCity, Collectors.averagingInt(CityIncome::getIncome)));

key of groupResult is city name,and value is the average income

Upvotes: 1

Prakash
Prakash

Reputation: 491

You could do it with a couple of variables for each gender, mCount, mTotal, fCount, fTotal.

Read the csv line by line, incrementing mCount or fCount appropriately and adding the salary to mTotal or fTotal.

After you reach the end of the file,

just do mTotal/mCount and fTotal/fCount to get your averages.

Upvotes: 0

Related Questions