假设我有两个数组,
String[] A= {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
String[] B= {"0", "2", "4", "6", "8", "10", "12"};
如何通过比较我想返回另一个数组和B中所有A值的方式比较两个数组?
返回数组:
String[] C= {"2", "4", "6","8","10"};
我读过this stackoverflow question,它本质上是在问同样的事情-但想知道Java中的等效语言是什么
答案中的C#代码:
string[] a1 = { "A","B", "C", "D" };
string[] a2 = { "A", "E", "I", "M", "Q", "U" ,"Y" };
string[] result = a1.Where(a2.Contains).ToArray();
答案 0 :(得分:3)
使用流API,您可以执行以下操作:
String[] result = Arrays.stream(a1)
.filter(new HashSet<>(Arrays.asList(a2))::contains)
.toArray(String[]::new);
编辑:
对于那些好奇是否会为每个元素构造一个新集合的人,根本不是这种情况。
仅一个构造了Set实例,上面的代码等效于:
List<String> list = new ArrayList<>();
HashSet<String> strings = new HashSet<>(Arrays.asList(a2));
for (String s : a1) {
if (strings.contains(s)) list.add(s);
}
String[] result = list.toArray(new String[0]);
答案 1 :(得分:2)
Set<String> a = new HashSet<>(Arrays.asList(a1));
Set<String> b = new HashSet<>(Arrays.asList(a2));
a.retainAll(b);
String[] results = a.toArray(new String[a.size()]);
答案 2 :(得分:0)
与下面的语句进行比较:
System.out.println("is A equals to B: " + Arrays.equals(A, B));
String [] joined = ObjectArrays.concat(A, B, String.class);
System.out.println("Joined Array" +joined);
有关数组比较的更多信息:
https://www.geeksforgeeks.org/java-util-arrays-equals-java-examples/