Priv
Priv

Reputation: 840

Get ordered Stream from LinkedHashMap

How can I get an ordered Stream from a LinkedHashMap<String,Object>?

I can get a sorted Stream using map.entrySet().stream().sorted(), but that will sort the items by their natural ordering, and does not support insertion order from the LinkedHashMap.

Upvotes: 0

Views: 359

Answers (1)

WJS
WJS

Reputation: 40034

It will occur naturally without any intervention. Note that I chose very large keys to avoid the likelyhood of collisions which would taint the demo.

    Random r = new Random(37);
    List<Integer> originalOrder = new ArrayList<>();
    Map<Integer,Integer> map = new LinkedHashMap<>();
    for (int i = 1; i < 10; i++) {
        int key = r.nextInt(1000000);
        int value = r.nextInt(100);
        originalOrder.add(value);
        map.put(key,value);
    }
    System.out.println(originalOrder);
    System.out.println(map.values());
    map.values().stream().forEach(a->System.out.print(" " + a + " "));
    System.out.println();
    map.entrySet().stream().forEach(a->System.out.print(" " + a.getValue() + " ")); 

Should print this or something similar

[23, 18, 26, 73, 0, 6, 91, 94, 31]
[23, 18, 26, 73, 0, 6, 91, 94, 31]
23 18 26 73 0 6 91 94 31
23 18 26 73 0 6 91 94 31

Upvotes: 3

Related Questions