How to put List elements to String Array in Java

Daniel Benedek :

Is there a way to put list elements to a String array in java? I sorted a Map by value using a custom Comparator and now trying to put the key(String) elements into an array. The only way I found is looping through the array and the sorted list at the same time and fill up the array that way but it only puts the last element into it.

Example: My map without sorting: {a=5, b=2, c=8, d=1}

After sorted with custom Comparator: [c=8, a=5, b=2, d=1]

Now I simply need to put the key values (c,a etc.) to the tuple final String[] lettersWithBigValues = new String[n] where n is the length of the tuple.

However, after:

for (int i = 0; i < Integer.parseInt(args[1]); i++) { System.out.println(lettersWithBigValues[i]+","); }

The console gives back: d,d,d,d given that the console line argument is 4

Here is the full function:

public String[] getTopLettersWithValues(final int n){
        final String[] lettersWithBigValues = new String[n];

        final Map<String, Integer> myMap = new HashMap<>();

        int counter = 0;

        for (final List<String> record : records) {

            if (!myMap.containsKey(record.get(1))) {
                myMap.put(record.get(1), counter += Integer.parseInt(record.get(4)));
            } else {
                myMap.computeIfPresent(record.get(1), (k,v) -> v + Integer.parseInt(record.get(4)));
            }
        }

        System.out.println(myMap);

        List<Map.Entry<String, Integer>> sorted = new LinkedList<>(myMap.entrySet());

        // Sort list with list.sort(), using a custom Comparator
        sorted.sort(valueComparator);

        System.out.println(sorted);

        for (int i = 0; i < lettersWithBigValues.length; i++) {
            for (Map.Entry<String, Integer> values: sorted) {
                lettersWithBigValues[i] = values.getKey();
            }
        }
         return lettersWithBigValues;
    }

Where records is a List of data read from a csv file.

And here is the comparator:

    public Comparator<Map.Entry<String, Integer>> valueComparator = (o1, o2) -> {

        Integer v1 = o1.getValue();

        Integer v2 = o2.getValue();

        return v2.compareTo(v1);
    };
Naman :

You can attain the array of keys as follows:

String [] lettersWithBigValues = myMap.entrySet().stream() // entries of your intial map
        .sorted(valueComparator) // sorted by your comparator
        .map(Map.Entry::getKey) // mapped to only the key e.g. 'd', 'a'
        .toArray(String[]::new); // converted to array

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=301020&siteId=1