Convert from one collection to anonther..? (Java in General forum at Coderanch)

Life is full of choices. Sometimes you make the good ones, and sometimes you have to kill all the witnesses. I think all implementations of Collection have a constructor, which takes another Collection and adds all the elements to the new object, like Speaking of Map type, we have a problem, since Map is not a Collection and it's entry needs two things - key and value, while Collections can provide only one element, so you have to populate a Map manually. A Map and a Set have different structures than a List, so there is no single, clear way to convert a List to a Map or Set. You can create a Set and add all the elements of the List to it. Since a Set cannot contain duplicate elements, the content of the Set might be different than what was in the original List: Note: Vector is a legacy collection class, you should not use it (unless there is a special reason to do so, for example because you're using an old API that expects a Vector). It's not so simple to convert a List to a Map, you'll have to decide what the keys and values in the Map are going to be, based on the elements in the List. Most Collection classes have a constructor that take any other Collection. Even if they don't, each Collection has the addAll method. If the collection allows adding elements then you can create an empty collection, then call this method: Map is more difficult since you want to convert a '1 dimensional' structure to a '2 dimensional' structure. What will the values for the keys be? The other way around (Map to Collection) will be easier since Map has three Collection views (keySet(), values(), entrySet()) which already turn the Map into a Collection (well, kind of). to classes belongs to same interface it is easy to convert....but for classes with differenent interface(taking about Map) is it difficult or not possible? No, you can not convert a Collection to a Map, because it has an entirely different structure. You would have to do this manually, and even that takes some effort as you have to specify keys and values, not just values like in a Collection. Source.


Яндекс.Метрика Рейтинг@Mail.ru Free Web Counter
page counter
Last Modified: April 18, 2016 @ 11:03 pm