Home > database >  add to dictionary values from list of lists in java
add to dictionary values from list of lists in java

Time:10-13

I have list of lists which called elephantList and this is the data on it :

elephantList : [[Term1, 3, d3, d5, d43 ], [Term2, 4, d1, d15, d46 ], [Term3, 3, d3, d5, d43], [Term1, 3, d4, d6, d7], [Term2, 4, d2, d3, d4], [Term3, 3, d5, d6, d77]]

what I need is to convert this list into ordered dictionary and I need d's to become also asc ordered and not duplicated. and become something like this. :

{Term1=[d3,d4,df,d6,d7,d43], Term2=[d1, d2,d3,d15,d46] ... etc }

So I did this :

for(int i = 0 ; i < elephantList.size() ; i   ){
    dictionary.put(elephantList.get(i).get(0),elephantList.get(i).subList(2,elephantList.get(i).size()));
}

but I just return this :

{Term2=[d2, d3, d4], Term1=[d4, d6, d7], Term3=[d5, d6, d77]}

which is not ordered and just last block of each term not all d's

How can I solve it ?

CodePudding user response:

To get an ordered map, a SortedMap should be used -- then it will be sorted by keys Term1, Term2, Term3

Similarly, to sort the values without duplicates, an ordered set should be used to store the values and in this case it should use custom comparator to sort d's as integers: d1, d2, d3, d15.

Occasional whitespaces in the d's should be trimmed off using String::trim.

SortedMap<String, SortedSet<String>> dictionary = new TreeMap<>();
for (List<String> current : elephantList) {
    dictionary.computeIfAbsent(current.get(0), k -> new TreeSet<>(
        Comparator.comparingInt(s -> Integer.parseInt(s.substring(1).trim()))
    ))
    .addAll(current.subList(2, current.size()));
}

Similar result can be achieved using Stream API: Collectors.groupingBy Collectors.flatMapping (Java 9 ) Collectors.toCollection:

SortedMap<String, SortedSet<String>> dictionary2 = data
    .stream()
    .collect(Collectors.groupingBy(
        lst -> lst.get(0),
        TreeMap::new,
        Collectors.flatMapping(lst -> lst.subList(2, lst.size())
            .stream(),
            Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparingInt(
                    s -> Integer.parseInt(s.substring(1).trim())
                ))
            )
        )
    ));

CodePudding user response:

Try this

    Map<String, List<String>> dictionary = new HashMap<>();
    for (List<String> current : elephantList) {
        List<String> toUpdate = dictionary.computeIfAbsent(current.get(0), ignore -> new ArrayList<>());
        toUpdate.addAll(current.subList(2, current.size()));
    }
  • Related