-5

I have a map in the following format that is populated at runtime.

  Map<String, List<VerificationDetail>>

I want to convert this to a List so that all values in Map are populated in the list. I tried with few approached but unable to populate the List with all the details available in the map.

Stalwart
  • 59
  • 4
  • 11
  • 1
    What did you try? What did not work? What do you want in the list? – Burkhard Apr 29 '16 at 04:06
  • Can you use Java 8 or not? – Louis Wasserman Apr 29 '16 at 04:13
  • @Burkhard . I tried the following List list = new ArrayList((Collection extends Value>) finalMap.values()); – Stalwart Apr 29 '16 at 04:16
  • @Louis. I cannot use Java 8 . using Java 6 – Stalwart Apr 29 '16 at 04:18
  • 2
    `for (Map.Entry> entry : map.entrySet()) al.addAll(entry.getValue());` remember each `value` in your `map` is a `List`! – Elliott Frisch Apr 29 '16 at 04:24
  • @Stalwart this isn't going to be a one-liner with base Java 6. – Louis Wasserman Apr 29 '16 at 04:27
  • So you want to create a `List` of `List` objects out of the `map` ? – Som Bhattacharyya Apr 29 '16 at 04:37
  • 1
    @ElliottFrisch Should use `values()`, not `entrySet()`. ;-) `List al = new ArrayList(); for (List values : map.values()) al.addAll(values);` – Andreas Apr 29 '16 at 04:45
  • Thanks Andreas. If I want to associate the key of the map to a String in the VerificationDetail and populate the values in the map to a List within VerificationDetail? (I dont want to have the same keys repeated again within the list) My List will be like below VerificationDetail.java ************************ String key; (Map's key) List - This will contain the map.values() associated with that particular key. – Stalwart Apr 29 '16 at 06:46

2 Answers2

0

Well, it isn't a one-liner but I guess it does the job!

// Map that has the details
Map<String, List<VerificationDetail>> map = new HashMap<>(1);

// Meanwhile some values are added to the map . . .

// The list where all your map values going to be inserted
List<VerificationDetail> allDetails = new ArrayList<>(1);

for (Map.Entry<String, List<VerificationDetail>> entry : map.entrySet()) {
    allDetails.addAll(entry.getValue());
}
lkallas
  • 1,310
  • 5
  • 22
  • 36
0

I might be answering late but this could help someone else, there is better way in java 8 to do this,

Map<String, List<VerificationDetail>> map = new HashMap<>();

List<VerificationDetail> combinedList = new ArrayList<VerificationDetail>();

map.values().forEach(o-> combinedList.addAll(o));

System.out.println(combinedList);
Manasi
  • 765
  • 6
  • 17