1

So I have list A and list B.
A is of size n and B is of size n + 1.
I need to know if all elements in A are the same as all elements in 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?

nicoqueijo
  • 872
  • 2
  • 11
  • 28

3 Answers3

1

List has a subList method, so you can express your conditions directly:

(b.size() == a.size() + 1) && (b.subList(0, a.size()).equals(a))
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

Very simple solution:

return B.take(A.size+1) == A
jbarat
  • 2,382
  • 21
  • 23
0

As long as b cannot be empty, you could write:

return a == b.dropLast(1)
Ben P.
  • 52,661
  • 6
  • 95
  • 123