我拥有的是一个名为 Id
的 String
对象数组,然后循环遍历 Id
对象以获取电子邮件地址与该 Id
关联(然后将它们连接起来)。我现在想从仅具有重复电子邮件地址的数组中删除 String
(通过查看 String
中的 Id
忽略)。
例如,String
数组包含以下 Id
对象:
{1, 2, 3}
现在,我连接与该 Id
关联的电子邮件地址,String
数组变为:
{1 - test@gmail.com, 2 - any@gmail.com, 3 - test@gmail.com}
因此,我需要删除重复的电子邮件(以及与其连接的 Id
)以提供以下内容:
{1 - test@gmail.com, 2 - any@gmail.com}
然后,我将使用 split 删除电子邮件地址,得到最终结果:
{1, 2}
所以我遇到的问题是,它当然会查找包括电子邮件和 ID 在内的整个字符串,但我只需要查找电子邮件地址,然后从数组中删除整个“字符串” .
我已经完成了这段代码:
//Remove all duplicate email addresses from list
ArrayList<String> duplicateEmails = new ArrayList<String>();
//looping through cform.getConsumers which is a String[] array of Id's, finding email address of that Id and concatenate it and add to the array list
for (String conId : cform.getToConsumers()){
Long consId = Long.parseLong(conId);
Consumer cons = af.getSingleConsumerId(consId);
duplicateEmails.add(conId + " - " + cons.getEmail());
}
//convert arraylist to String array
String[] stringArray = duplicateEmails.toArray(new String[0]);
//remove the duplicates
Set<String> findDuplicates = new HashSet<String>(Arrays.asList(stringArray));
String[] removedEmails = findDuplicates.toArray(new String[0]);
最佳答案
您可以执行以下操作:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class Testing {
public static void main(String[] args) {
HashMap<String, String> hm = new LinkedHashMap<String, String>();
String[] values = {"1","2","3"};
ArrayList<String> ar = new ArrayList<String>();
ar.add("test@gmail.com");
ar.add("any@gmail.com");
ar.add("test@gmail.com");
for (int i = 0; i<ar.size();i++) {
if (!hm.containsKey(ar.get(i)))
hm.put(ar.get(i), values[i]);
}
System.out.println(hm);
}
}
输出:
[1, 2]
关于java - 仅在 Java 中通过查看字符串的特定部分来删除字符串数组的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939836/