-
Notifications
You must be signed in to change notification settings - Fork 88
/
ArrayList16
56 lines (41 loc) · 1.2 KB
/
ArrayList16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Java program to convert ArrayList
// to HashMap
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class ArrayListExample {
public static void main(String[] args)
{
// ArrayList of string
ArrayList<String> languageList
= new ArrayList<>(Arrays.asList("Java", "C++", "Python",
"PHP", "NodeJS"));
System.out.println(
"-------------ArrayList---------------");
// printing the ArrayList
for (String language : languageList)
{
System.out.println(language);
}
System.out.println(
"--------------HashMap----------------");
// convertArrayListToHashMap() method directly
// converts ArrayList to Hashmap
HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList);
// printing the HashMap
for (Map.Entry<String, Integer> entry : languageMap.entrySet()) {
System.out.println(entry.getKey() + " : "
+ entry.getValue());
}
}
private static HashMap<String, Integer>
convertArrayListToHashMap(ArrayList<String> arrayList)
{
HashMap<String, Integer> hashMap = new HashMap<>();
for (String str : arrayList) {
hashMap.put(str, str.length());
}
return hashMap;
}
}