'How to re-order Map items based on the user input?
I am trying to do something similar to the Huffman tree. When I type zzzbbbbbbbbbaaaaacc, the Map I get is this : [a=5, b=9, c=2, z=3]
I think it orders it in alphabetical order but that is not what I want. I want to have the order like this : [z=3, b=9, a=5, c=2] (the user input starts with z, then b, then a, then c).
My code looks like this for now :
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
Queue<Character> fifo = new LinkedList<Character>();
for (Character character : s.toCharArray()) {
fifo.add(character);
}
List<String> distinctElements = s.chars().mapToObj(e -> Character.toString((char) e)).distinct()
.collect(Collectors.toList());
Map<Character, Long> characters = s.chars().distinct().mapToObj((e -> (char) e))
.collect(Collectors.toMap(c -> c, c -> s.chars().filter(ch -> ch == c).count()));
Solution 1:[1]
You can use a toMap collector with a map constructor argument:
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import static java.util.stream.Collectors.toMap;
public class MapFromString {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
String s = scan.nextLine();
Map<Character, Integer> map = s.chars()
.boxed()
.collect(
toMap(c -> Character.valueOf((char) c.intValue()),
c -> 1,
Integer::sum,
LinkedHashMap::new));
System.out.println(map);
}
}
}
Solution 2:[2]
You should be using a LinkedHashMap, this structure maintains the order of elements inserted into it.
This guide has some examples to see it in action: https://www.baeldung.com/java-linked-hashmap
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Sveshnikov |
| Solution 2 | AlexMelgar |
