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,LinkedHashSetkeeps 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
相关产品推荐
相关产品推荐

