String[][] users =
new String[][] {{"xiaoming", "abc@123.com", "abc@12.com" },
{"xiaoming", "abc@123.com", "a@163.com" },
{"lidan", "abcd@11.com", "ab@qq.com" },
{"lidan", "abc@12.com", "abcd@11.com" } };
int size = users.length;
int[] num = new int[size]; //初始化用户对应的索引
for (int i = 0; i < size; i++)
{
num[i] = i;
}
Map<String, Integer> map = new HashMap<>(); //存储邮箱对应的用户索引
for (int j = 0; j < size; j++)
{
for (int k = 1; k < users[j].length; k++)
{
String email = users[j][k];
Integer index = map.get(email);
//如果邮箱不存在,把当前邮箱及对应的用户索引放到map中;
//如果邮箱已存在,那么将当前用户的合并位置指向到索引为value的用户;
if (index == null)
{
map.put(email, j);
}
else
{
num[j] = index;
}
}
}
//执行完成后num = [0, 0, 2, 0],意味着第二、第四个用户合并到第一个用户里
//合并输出
//1、先转为list好合并
List<List<String>> data = new ArrayList<>(size);
for (int i = 0; i < size; i++)
{
data.add(new ArrayList(Arrays.asList(users[i])));
}
//2、合并
for (int z = 1; z < size; z++)
{
int point = num[z];
if (point != z)
{
List<String> item = data.get(z);
item.remove(0);
data.get(point).addAll(item);
data.set(z, null);
}
}
//移除null
data.removeAll(Collections.singleton(null));
//输出
for (int i = 0; i < data.size(); i++)
{
System.out.println(data.get(i));
}
合并相同邮箱的用户
最新推荐文章于 2024-07-15 14:12:48 发布