Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

Counting number of duplicates using Arraylist in Java

I have a zip code file which has the zip code in the format Zipcode,city,county

90001,Los Angeles,Los Angeles
90002,Los Angeles,Los Angeles
90003,Los Angeles,Los Angeles
90004,Los Angeles,Los Angeles
90005,Los Angeles,Los Angeles

I have created a list which holds the objects of Zipcode class. What I'm trying is to count the number of zipcodes in a county and print it. Something like this:

Los Angeles: 525
San Diego: 189
Orange: 149

etc.

This is the code I've tried so far:

void printInfo() {
        int count=0;
        Collections.sort(zipcodes);    //natural order of county
        for (int i = 0; i < zipcodes.size()-1;i++)
        {
            for (int j = i+1; j < zipcodes.size(); j++)
            {
                if (zipcodes.get(i).county.equals(zipcodes.get(j).county)) {
                    count++;
                }
            }
            state.add(new County(zipcodes.get(i).county,count));
        }


        Collections.sort(state);
        for (County z: state) {
            System.out.println("County: " + z.county + " " + "Count: " + z.count );     
        }
}

The output I'm getting looks like: Los Angeles: 148 Orange: 148 San Diego: 148 Los Angeles: 149 San Diego: 149 ..... Los Angeles: 188 San Diego: 188 ..... Los Angeles: 524

Need help. Not sure what I'm doing wrong in this loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@MSG Much simpler solution (assuming that zipCodes is a List < ZipCode > )

    Map<String, Long> processed = zipCodes.stream()
            .collect(Collectors.groupingBy(ZipCode::getCounty, Collectors.counting()
        )                        
    );

    processed.entrySet().stream().forEach(zipCode -> System.out.println(zipCode));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...