![]() List valueList = students.values().stream().collect(Collectors.toList()) We'll steam() the keys and values of a Map, and then collect() them into a List: List keyList = students.keySet().stream().collect(Collectors.toList()) This results in: Key List: Ĭonvert Map to List with Collectors.toList() and Stream.map() List valueList = new ArrayList(students.values()) ![]() The values() method returns a Collection of the values in the map, and naturally, since a List implements Collection, the conversion is as easy as passing it in the List's constructor: List keyList = new ArrayList(students.keySet()) Due to the flexibility of Java Collections - we can create a List from a Set simply by passing a Set into a List's constructor. The keySet() method returns a Set of all the keys, which is to be expected, since keys have to be unique. Thankfully, we can easily access the keys and values of a map through the keySet() and values() methods. Since Maps are two-dimensional collections, while Lists are one-dimensional collections - the other approach would be to convert a Map to two Lists, one of which will contain the Map's keys, while the other would contain the Map's values. One of the Collectors we can use is Collectors.toList(), which collects elements into a List. Since Streams are not collections themselves - they just stream data from a Collection - Collectors are used to collect the result of a Stream's operations back into a Collection. The entrySet() method returns a Set of Map.Entry elements, which can easily be converted into a List, given that they both implement Collection: List> singleList = students.entrySet() ![]() The easiest way to preserve the key-value mappings of a Map, while still converting it into a List would be to stream() the entries, which consist of the key-value pairs. Streams work wonderfully with collections, and can aid us in converting a Map to a List. Java 8 introduced us to the Stream API - which were meant as a step towards integrating Functional Programming into Java to make laborious, bulky tasks more readable and simple. In this tutorial, we'll take a look at how to convert a Java Map to a Java List: Though, this doesn't stop us from converting Maps to Lists through several approaches. The key difference is: Maps have two dimensions, while Lists have one dimension. (String.format( "Third element: %s", list.get( 2)) Each element has an index and is uniquely identified by it: List list = new ArrayList(Arrays.asList( "James", "Amy", "Young")) A Java List implementation is a collection that sequentially stores references to elements.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |