Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

Scala difference of two lists

I have two lists:

val list1 = List("word1","word2","word2","word3","word1")
val list2 = List("word1","word4")

I want to remove all occurrences of list2 elements from list1, i.e. I want

List("word2","word2","word3") <= list1 *minus* list2

I did list1 diff list2 which gives me List("word2","word2","word3","word1") which is removing only the first occurrence of "word1".

I can not convert it to sets because I need knowledge about duplicates (see "word2" above). What to do?

question from:https://stackoverflow.com/questions/16278098/scala-difference-of-two-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can

val unwanted = list2.toSet
list1.filterNot(unwanted)

to remove all items in list2. (You don't need knowledge of duplicates in list2.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...