在java中对集合进行连接和析取的最佳方法
在两个ArrayList上创建在java中对集合进行连接和析取的最佳方法,java,arrays,collections,arraylist,Java,Arrays,Collections,Arraylist,在两个ArrayList上创建和和或方法的最有效方法是什么 //not coded in java HashSet<String> first = {"hello", "to", "you"} HashSet<String> second = {"hello", "to", "me"} HashSet<String> and = and(first, second) = {"hello", "to"} HashSet<String> or
和
和或
方法的最有效方法是什么
//not coded in java
HashSet<String> first = {"hello", "to", "you"}
HashSet<String> second = {"hello", "to", "me"}
HashSet<String> and = and(first, second) = {"hello", "to"}
HashSet<String> or = or(first, second) = {"hello", "to", "you", "me"}
//未用java编码
HashSet first={“您好”,“收件人”,“您”}
HashSet second={“你好”,“对”,“我”}
HashSet和=和(第一,第二)={“你好”,“到”}
HashSet or=或(第一,第二)={“你好”,“对”,“你”,“我”}
我需要实现这两种方法(非常简单),但我需要高效地实现,因为我将对具有数百个字符串的集合执行
和和或。有小费吗 你可以使用Set,只需施放即可
List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>(list);
List List=new ArrayList();
Set Set=新哈希集(列表);
使用它的方法来实现这一点为了避免混淆,我将调用方法intersection
和union
,因为和和或的含义有点模糊
Set
上有一种方法可以完成交叉口的工作。你需要注意我的警告
在集合
上有一种方法可以完成联合的工作
以下是一个例子:
public static void main(String[] args) throws Exception {
final Set<String> first = new HashSet<>(Arrays.asList("hello", "to", "you"));
final Set<String> second = new HashSet<>(Arrays.asList("hello", "to", "me"));
System.out.println(intersection(first, second));
System.out.println(union(first, second));
}
public static Set<String> intersection(final Set<String> first, final Set<String> second) {
final Set<String> copy = new HashSet<>(first);
copy.retainAll(second);
return copy;
}
public static Set<String> union(final Set<String> first, final Set<String> second) {
final Set<String> copy = new HashSet<>(first);
copy.addAll(second);
return copy;
}
publicstaticvoidmain(字符串[]args)引发异常{
final Set first=新的HashSet(Arrays.asList(“hello”、“to”、“you”));
final Set second=新哈希集(Arrays.asList(“hello”、“to”、“me”));
System.out.println(交叉点(第一、第二));
System.out.println(联合(第一,第二));
}
公共静态集交叉点(第一个最终集,第二个最终集){
最终集副本=新哈希集(第一);
副本。保留(第二);
返回副本;
}
公共静态集合并集(第一个最终集合,第二个最终集合){
最终集副本=新哈希集(第一);
复制。添加全部(第二);
返回副本;
}
注意使用Set
而不是List
。这有两个目的:
集合
具有O(1)
包含
,与列表的O(n)
相反。这有助于解决交叉口问题
Set
保证唯一性。这有助于工会
还要注意,我在执行操作之前复制了集合——因为Java按值传递引用,不复制会导致更改原始集合
如果需要保留顺序,则需要使用LinkedHashSet
,因为HashSet
没有顺序。您希望使两个ArrayList相交并。
我认为这是一个重复的问题。
我建议看一看这个帖子:
提供了一个addAll
(并集或“或”方法)和一个retainAll
(交集或“和”方法)。因此,如果可以管理,最好使用支持这些操作的Set
s,或者如果不太昂贵,最好将列表转换为集合,并利用现有的内容。是否将列表视为集合?是否保证元素只出现一次?如果没有,你希望(比如说){a”,“b”,“a”}
和{b”,“a”,“b”}
发生什么?谢谢@ChrisHayes非常有用!您指向其他答案的链接错误地指向Set
javadoc.retainal是“and”,addAll是“or”。我错了吗?对不起,是的。我用的是更传统的用法-在你的用法中,我把它倒过来了。这不是英语,这是编程-cast有一个。