简体   繁体   English

Kotlin 检查两个列表是否相同,除了一个具有附加元素的列表?

[英]Kotlin check if two lists are the same apart from one list having an additional element?

So I have list A and list B.所以我有清单A和清单B。
A is of size n and B is of size n + 1. A 的大小为 n,B 的大小为 n + 1。
I need to know if all elements in A are the same as all elements in B.sublist(0, n - 1).我需要知道 A 中的所有元素是否与 B.sublist(0, n - 1) 中的所有元素相同。

A: [5,7,2,9]  
B: [5,7,2,9,1]
true

A: [5,7,2,9]  
B: [5,7,2,9,9]
true

A: [7,5,2,9]  
B: [5,7,2,9,1]
false (order matters)

Is there any elegant ways to do this using library functions maybe?是否有任何优雅的方法可以使用库函数来做到这一点?

List has a subList method, so you can express your conditions directly: List有一个subList方法,所以你可以直接表达你的条件:

(b.size() == a.size() + 1) && (b.subList(0, a.size()).equals(a))

Very simple solution:非常简单的解决方案:

return B.take(A.size+1) == A

As long as b cannot be empty, you could write:只要b不能为空,你就可以写:

return a == b.dropLast(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过比较两个列表从一个列表中删除元素 - How to remove element from one list by comparing two lists 从两个列表中过滤具有相同属性的对象并更新它们并将其存储在 Java 8 中的第三个列表中 - Filter Objects having the same property from two Lists and Update them and Store it in a 3rd List in Java 8 从同一个pojo数组创建了两个列表,修改了一个列表,同样的事情也会影响其他列表 - Created two Lists from same pojo array, Modifying one List, same thing affects on other list also 从同一个数组创建两个列表,修改一个列表,更改另一个列表 - Created two Lists from same array, Modifying one List, changes the other 在对一个列表的元素进行排序后,检查两个列表的顺序是否相等 - Check two lists for order equality after sorting elements of one list 检查一个列表是否包含来自另一个列表的元素 - Check if one list contains element from the other 如何将两个列表中的每个元素连接到一个新列表中? - how concat each element from two lists to a new one? 比较列表列表中的一个元素 - Comparing one element in a list of lists 检查两个集合是否包含至少一个相同元素的快速方法 - fast way to check if two sets contain at least one same element 检查列表列表是否包含列表中的任何子列表匹配元素 - Check If List of Lists Contains Any Sub List Matching Element from List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM