如何结合2个字符串数组,但保留Java中的副本?

时间:2013-03-31 08:39:21

标签: java arrays string union

s1={"phone","smartphone","dumpphone"} (all string elements in s1 are unique)
s2={"phone","phone","smartphone"}

(s2中的字符串元素可以复制,但s2中的每个元素必须属于s1,即s2不能包含s1中不存在的字符串。例如,s2不能包含“掌上电脑”,因为s1不包含“” 手持式 “”)

s2 union s1={"phone","phone", "smartphone","dumpphone"}

Set& HashSet不允许重复

我尝试了List,但没有帮助。

你知道怎么解决吗?

1 个答案:

答案 0 :(得分:1)

List实现应该可以正常工作。这是使用ArrayList的代码:

String[] s1 = new String[]{"phone","smartphone","dumpphone"};
String[] s2 = new String[]{"phone","phone","smartphone"};

ArrayList<String> union = new ArrayList<>();
// Add elements of s1
for(String s : s1){ union.add(s); }
// Conditionally add elements of s2
for(String s : s2){ if(union.contains(s)){ union.add(s); } }

结果:

for(String s : union){ System.out.println(s); }

打印

phone
smartphone
dumpphone
phone
phone
smartphone

注意:你说你只期待两次“手机”的发生。为什么?从您的问题陈述来看,目前尚不清楚。

修改

根据@dantuch在下面的评论,你可能正在寻找类似的东西:

String[] s1 = new String[]{"phone","smartphone","dumpphone"};
String[] s2 = new String[]{"phone","phone","smartphone"};

ArrayList<String> union = new ArrayList<>();
// Add elements of s2
for(String s : s2){ union.add(s); }
// Conditionally add elements of s1 (Only if they're not in s2)
for(String s : s1){ if(!union.contains(s)){ union.add(s); } }

哪个会打印:

phone
phone
smartphone
dumpphone