对字符串进行归类

11 篇文章 0 订阅

使用Map来对字符串进行归类

将数组{“h1”, “h2”, “h2”, “h3”, “h4”, “h4”, “h4”}进行归类,即转换成h1,h2*2,h3,h4*3的形式。

    private String formatExecHosts(Map<String, Integer> hm) {
        if (hm == null || hm.size() < 1) {
            return null;
        }
        StringBuffer hosts = new StringBuffer();
        for (String key : hm.keySet()) {
            if (hm.get(key) == 1) {
                hosts.append(key);
            } else {
                hosts.append(key);
                hosts.append("*");
                hosts.append(hm.get(key));
            }
            hosts.append(",");
        }
        return hosts.substring(0, hosts.length() - 1);
    }

将机器名和个数放入map

    private static Map<String, Integer> mergeHost(Object[] objs) {
        if (objs == null || objs.length < 1) {
            return null;
        }
        Map<String, Integer> hm = new HashMap<String, Integer>();
        for (Object execHost : objs) {
            String h = execHost.toString();
            if (!checkHost(hm, h)) {
                hm.put(h, 1);
            }
        }
        return hm;
    }

若hm中不存在key为host的记录,则返回false;若存在记录,则数值加1,hm.put(h, num)覆盖掉之前的记录

    private static boolean checkHost(Map<String, Integer> hm, String host) {
        Iterator<String> it = hm.keySet().iterator();
        while (it.hasNext()) {
            String h = it.next();
            if (h.equals(host)) {
                Integer num = hm.get(h) + 1;
                hm.put(h, num);
                return true;
            }
        }
        return false;
    }

测试

    public static void main(String[] args) throws Exception {
        Object[] arr = new Object[]{"h1", "h2", "h2", "h3", "h4", "h4", "h4"};
        System.out.println(formatExecHosts(mergeHost(arr)));
    }

测试结果
在这里插入图片描述

go语言对字符串进行归类

// h1, h1, h2 -> h1*2, h2
func formatHosts(hosts map[string] int) string {
	hs := []string{}
	for h, n := range hosts {
		if n > 1 {
			hs = append(hs, fmt.Sprintf("%s*%d", h, n))
		} else {
			hs = append(hs, h)
		}
	}
	return strings.Join(hs, commaSep)
}

func mergeHost(hosts []string) map[string] int {
	hm := make(map[string] int)
    for _, h := range hosts {
		if _, ok := hm[h]; ok {
			hm[h] += 1
		} else {
			hm[h] = 1
		}
	}
	return hm
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值