When programming in Java, both training and non-training I think List, Map, etc. often appear (sometimes Set, Iterator, etc.).
However, what is converted after a long time Because it should be "that? How do you convert this?"
Static methods for those with class names, instance methods for those with only method names
\ Conversion destination Conversion source|List, Set, etc.(Collection) |
Map | Iterator | Stream | Array |
---|---|---|---|---|
List/Set etc. (Collection) |
constructor | - | iterator() | stream() |
Map | entrySet(), keySet(), values() | constructor | (Via Set) | (Via Set) |
Stream | Collect() | Collect() | iterator() | Intermediate operation in general |
Array | (List only) Arrays.asList()※ |
- | (Via List) | Steam.of() |
Java's built-in Collection classes (ArrayList, HashSet, ArrayDeque, etc.) Some constructors put a Collection in it. Map is not a Collection, but you can do the same with Map → Map.
Collection.java
//Prepare Set in advance
Set<String> ESet = Set.of("list","set","deque");
//Set to List!
List<String> EList = new ArrayList(Eset);
If you want only the key list, use keySet. If you want only the contents, use values (). entrySet () if you want to use both in the for statement
Map.java
//Prepare Map in advance
Map<String,Collection<String>> EMap = new HashMap<>();
EMap.put("list",List.of("list"));
EMap.put("set",Set.of("set"));
//Map to Set!
Set<String> ESet = EMap.keySet();
//Set to Iterator!
ESet.iterator();
//Map → Iterator is also possible by connecting
EMap.keySet().iterator();
List.java
List<String> EList = List.of("list","set","deque");
String[] EArray = EList.toArray(new String[0]);
From Stream, you can make it a Collection by using collect (). (It is also possible to use other than Collection such as array and Map) In particular, you can easily create almost any Collection by using Collectors.toCollection.
Set.java
List<String> EList = List.of("list","set","deque");
//Convert to Set
Set<String> ESet = EList.stream().collect(Collectors.toSet());
Note: ** Collectors.toSet () and Collectors.toList () are not guaranteed to be modifiable or impossible! **
(Example: toList is currently an ArrayList, but it may suddenly become an immutable List)
Map.java
List<Integer> EList = List.of(1,2,3);
//Convert the element of the list to the key and the string to the Map to set the value
Map<Integer,String> EMap = EList.stream().collect(Collectors.toMap(Function.identity(), String::valueOf));
LinkedList.java
List<Integer> EList = List.of(1,2,3);
//If you want to specify the implementation class of List, use toCollection
LinkedList<Integer> EList = EList.stream().collect(Collectors.toCollection(LinkedList::new));
Recommended Posts