假设我有两个数组,String[] A= {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};String[] B= {"0", "2", "4", "6", "8", "10", "12"};如何比较两个数组,以返回另一个包含 A 中 B 中所有值的数组?返回数组: String[] C= {"2", "4", "6","8","10"};想知道 Java 中的等价物是什么答案中的 C# 代码:string[] a1 = { "A","B", "C", "D" };
string[] a2 = { "A", "E", "I", "M", "Q", "U" ,"Y" };
string[] result = a1.Where(a2.Contains).ToArray();
3 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
使用流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]);
汪汪一只猫
TA贡献1898条经验 获得超8个赞
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()]);
江户川乱折腾
TA贡献1851条经验 获得超5个赞
比较适用于以下声明:
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);
添加回答
举报
0/150
提交
取消