如何转换EnumSet <a> to Set<b>

时间:2019-04-23 08:52:16

标签: kotlin enums set enumset

I have an enum class thats something like this:

enum class SomeType(val id: String) {
    TYPE1("A"),
    TYPE2("B"),
    TYPE3("C"),
    TYPE4("D")
}

Now, I need to filter a list of Something which has a String that's stated in SomeType enum. So Basically I have something like this:

class Something(val id: String)
// where the value of id is one of the value of the SomeType's id

I have a list of Something like so:

val somethingList = arrayListOf<Something>(
    Something("A"),
    Something("B"),
    Something("A"),
    Something("C"),
    Something("D"),
    Something("A"),
    Something("D")
)

Now I need to filter that somethingList to by the given EnumSet<SomeType>.

So if I have a:

val someTypeSet = EnumSet.of(SomeType.Type3, SomeType.Type2)

the resulting filtered List should be,

val filteredList = arrayListOf<Something>(
    Something("B"),
    Something("C")
)

My idea is to convert the someTypeSet to a Set<String> and just do something like:

Set<String> setOfSomeTypeIds = convertToSet(someTypeSet)
val filteredList = somethingList.filter { something ->
    setOfSomeTypeIds.contains(something.id)
}

Can someone guide me how to convert an EnumSet to a Set of its value?

I also explained the whole process just in case there is a better solution to the problem above.

Anything will be appreciated.

Thanks in advance.

2 个答案:

答案 0 :(得分:1)

过滤相关类型后,可以使用map函数。

val filteredSomethings:List<Something> = someTypeSet.filter { something ->
            setOfSomeTypeIds.contains(something.id) }.map { Something(it.id) }

它将返回带有相关ID的Something列表。

答案 1 :(得分:1)

您可以在任何集合上使用map将其转换为具有所需值的新集合...即someTypeSet.map { it.id }已经返回了字符串列表。如果您确实想拥有Set,也可以使用类似mapTo的名称。关于使用filter关键字也可以简化的in,例如:somethingList.filter { it.id in setOfSomeTypeIds }

因此总结:

val setOfSomeTypeIds = someTypeSet.map { it.id }

val filteredList = somethingList.filter { it.id in setOfSomeTypeIds }