Jai
Jai

Reputation: 131

What is the order of array when derived from Linked hashMap?

I have created one linked hash map and then using that map I have generated Map key array like this : -

Map<String, String> map = new LinkedHashMap<>();
map.put("Str1", "Str1");
map.put("Str1", "Str1");

String[] keyArray= map.keySet().stream.toArray(String[]::new);

Now, the question is what will be the order of keyArray ? Is it the same as inserrtion order of linked hashmap or different? If it is different then how can we generate an array with same insertion order which linkedhashmap has ?

Upvotes: 0

Views: 187

Answers (1)

ldz
ldz

Reputation: 2215

From the java.util.stream docs:

Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not. Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream, and others may render an ordered stream unordered, such as BaseStream.unordered().

From the LinkedHashMap docs

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order)

Since LinkedHashMap is used as a source and it is maintaining an ordering, the resulting array can be expected to have the same ordering as its source.

Upvotes: 1

Related Questions