简体   繁体   English

如何在 Java 中将 List 元素放入 String Array

[英]How to put List elements to String Array in Java

Is there a way to put list elements to a String array in java?有没有办法在java中将列表元素放入字符串数组? I sorted a Map by value using a custom Comparator and now trying to put the key(String) elements into an array.我使用自定义比较器按值对 Map 进行排序,现在尝试将 key(String) 元素放入数组中。 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}示例:我的地图没有排序: {a=5, b=2, c=8, d=1}

After sorted with custom Comparator: [c=8, a=5, b=2, d=1]使用自定义比较器排序后: [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.现在我只需要将键值( c,a等)放入元组final String[] lettersWithBigValues = new String[n]其中n是元组的长度。

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控制台返回: d,d,d,d假设控制台行参数为 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.其中记录是从 csv 文件读取的数据列表。

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);
    };

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

Seems to me that you have mistakenly used a nested for loop, you just need the one:在我看来,您错误地使用了嵌套 for 循环,您只需要一个:

for (int i = 0; i < lettersWithBigValues.length; i++) {
     lettersWithBigValues[i] = sorted.get(i).getKey();
}

That would return the array: c, a, b, d这将返回数组: c, a, b, d

As an added suggestion you could also have created the Comparator using the Entry.comparingByValue() method.作为附加建议,您还可以使用Entry.comparingByValue()方法创建Comparator器。

Comparator<Entry<String,Integer>> valueComparator = 
                Entry.<String,Integer>comparingByValue().reversed();

It returns a ready made Comparator that compares by the natural order of the value.它返回一个现成的Comparator ,按值的自然顺序进行比较。 So to sort in reverse, you just need to tag on the reversed() method which is defined in the Comparator interface.所以要反向排序,你只需要在Comparator接口中定义的reversed()方法上做标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM