开发者

Java Collections List : Converting from List '<Column <String1, String2>>' to 'List <String1>'

I have a function that returns a list like this:-

List <Column <String1, String2>>

Next I want to pass this list to a 2nd function, but 2nd function just needs a list which contains only 1st part (string1) of the Column(s) of the above list.

So I want pass just this list to 2nd function:-

List <String1>

my use case: Both the functions are from a library that I use to access database(Cassandra) for a web application. 1st function gives me a list of all columns which has two parts name(String1) and value(String2). So 1st function gives me a list of all columns(each of which has two strings) then I just need to use the list of column names to supply it to 2nd function that'll query the DB for those columns.

Since I need to do this job atleast 2-3 times before asking for data from DB for a single page, I need a superfast and开发者_Python百科 a reasonably efficient method to do so.


It depends on what you mean by "efficient" (memory, execution time, something else?) and what that second function is doing.

If you care about speed and the second function is going to be looking at the items in the list repeatedly, then you should probably just copy the strings into a new List<String>:

List<String> strings = new ArrayList<String>(input.size());
for (Column<String, String> column : input) {
    strings.add(column.name());
}
return strings;

If, on the other hand, the second function is going to only look at a small subset of the items or if you care more about memory than speed then you probably want a lazy view that converts items as they are accessed. Lists.transform from Google Guava can do this for you:

return Lists.transform(input, new Function<Column<String, String>, String>() {
    public String apply(Column<String, String> column) {
        return column.name();
    }
};

Note that you may want to create he Function as a separate static class unless you're ok with it holding onto a reference to your enclosing instance. I used an anonymous class here for brevity/clarity.


I believe there is no simpler way than simply walking over the first list and ask each Column for its String1 and then add that value to your List<String1>.

If you want to separate the walking and the adding, then consider writing an Iterator which returns all the String1's from the first list, and then use traverse that.


In Scala, you could just do:

stringsList = columnsList.map(_.string2)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜