如何在Java中计算列表对象中的重复值? [英] How to count duplicate values in the list object in Java?

查看:59
本文介绍了如何在Java中计算列表对象中的重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我有一个像这样的数组:

in java, i have an array like this:

String[] city = {"texas", "ny", "sydney", "ny", "paris", "texas", "ny"};

我想用计数对它们进行排序/分组...就像-

i want to sort/group them with count...like-

texas = 2
ny = 3
sydney = 1
paris = 1


推荐答案

使用 Collections.frequency()方法

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test{
    public static void main(String[] args) {
        String[] city = {"texas", "ny", "sydney", "ny", "paris", "texas", "ny"};
        List<String> asList = Arrays.asList(city);
        Map<String, Integer> map= new HashMap<String, Integer>();
        for(String s: city){
            map.put(s,Collections.frequency(asList,s));
        }
        System.out.println(map);

    }
}

这篇关于如何在Java中计算列表对象中的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆