You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现从逗号分隔字符串提取唯一手机号并统计数量

Java Solution to Extract Unique Mobile Numbers

Hey there, here's a clean way to get unique mobile numbers from your input string (while keeping the order of first occurrence) and count them, matching the output you need:

Approach

  • Split the input string into individual mobile number strings using the comma delimiter.
  • Use a LinkedHashSet to store these numbers: this collection automatically removes duplicates and maintains the order of first insertion, which aligns with your desired output.
  • Convert the set back to a comma-separated string using String.join().
  • The size of the set gives you the count of unique numbers.

Code Implementation

public class UniqueMobiles {
    public static void main(String[] args) {
        String mobiles = "1234567890,0987654321,1234567890,1122334455";
        
        // Split the string into individual mobile numbers
        String[] mobileArray = mobiles.split(",");
        
        // Use LinkedHashSet to preserve order and remove duplicates
        java.util.Set<String> uniqueMobiles = new java.util.LinkedHashSet<>();
        for (String num : mobileArray) {
            uniqueMobiles.add(num);
        }
        
        // Convert back to comma-separated string
        String uniqueMobilesStr = String.join(",", uniqueMobiles);
        int count = uniqueMobiles.size();
        
        // Output the result
        System.out.println("mobiles = \"" + uniqueMobilesStr + "\"; int count = " + count + ";");
    }
}

Explanation

  • Splitting the string: split(",") breaks the input into an array where each element is a mobile number.
  • LinkedHashSet: Unlike a regular HashSet, LinkedHashSet keeps track of the order in which elements are added, so your unique numbers stay in the order they first appeared in the input. Adding duplicates has no effect, so only unique entries are retained.
  • String.join: This method takes the set (which is iterable) and joins its elements with commas to recreate the formatted string.
  • Count: The size() method of the set directly gives the number of unique mobile numbers.

When you run this code, it will output exactly what you requested:

mobiles = "1234567890,0987654321,1122334455"; int count = 3;

内容的提问来源于stack exchange,提问作者A Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:33:12