能否从LinkedHashMap中提取键集,对其应用排序算法,然后将其放回映射中?

huangapple go评论72阅读模式
英文:

Is it possible to extract the key set from a LinkedHashMap, apply a sorting algorithm on it and put it back into the map?

问题

我有一个包含杂货商品列表的.csv文件,其中包含它们的UPC代码和产品名称。我已经编写了一些代码将产品的代码和名称放入了一个映射中,并且它们工作得很好(下面显示了代码)。在不使用TreeMap或与Map接口直接相关的任何内容的情况下,如何将映射的键集提取到一个列表中,并对其应用排序算法(例如快速排序),并输出那些带有其分配值的已排序键?(排序算法我自己可以编写,所以不是问题)。键和值是唯一的。

我可以更改方法,改为使用数组列表而不是映射,并直接在其上应用排序算法。我也知道有很多优秀的方法围绕使用Map接口来进行排序,但这只是为了练习,并且我很好奇如何实现类似的内容。

我的物品列表看起来像这样(我使用第二行数据行'upc14'作为键,最后一行数据行'name'作为值):

grp_id,upc14,upc12,brand,name
1,00035200264013,035200264013,Riceland,Riceland American Jazmine Rice
2,00011111065925,011111065925,Caress,Caress Velvet Bliss Ultra Silkening Beauty Bar - 6 Ct
3,00023923330139,023923330139,Earth's Best,Earth's Best Organic Fruit Yogurt Smoothie Mixed Berry
4,00208528800007,208528800007,Boar's Head,Boar's Head Sliced White American Cheese - 120 Ct
5,00759283100036,759283100036,Back To Nature,Back To Nature Gluten Free White Cheddar Rice Thin Crackers
6,00074170388732,074170388732,Sally Hansen,Sally Hansen Nail Color Magnetic 903 Silver Elements
7,00070177154004,070177154004,Twinings Of London,Twinings Of London Classics Lady Grey Tea - 20 Ct
8,00051600080015,051600080015,Lea & Perrins,Lea & Perrins Marinade In-a-bag Cracked Peppercorn
9,00019600923015,019600923015,Van De Kamp's,Van De Kamp's Fillets Beer Battered - 10 Ct
10,00688267141676,688267141676,Ahold,Ahold Cocoa Almonds
public class ReadFile {

    // 文件读取部分
    private static Map<Long, String> readFromCSV() {
        Map<Long, String> map = new LinkedHashMap<>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader("Grocery_UPC_Database.csv"));
            reader.readLine();
            String line = reader.readLine();
            while (line != null) {
                String[] attributes = line.split(",");
                for (int i = 1; i < attributes.length; i++) {
                    map.put(Long.parseLong(attributes[1]), attributes[4]);
                }
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    private static void createFile(Map<Long, String> map) {
        PrintWriter out = null;
        try {
            out = new PrintWriter("output.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            assert out != null;
            out.println(entry.getValue());
        }
        assert out != null;
        out.close();
    }

    public static void main(String[] args) {
        Map<Long, String> map = readFromCSV();
        createFile(map);
    }
}
英文:

I have .csv file that has a list of grocery items that has their UPC code and the product name. I already wrote some code to put the product's code and its name into a map and they are working fine (code shown below). Without using a TreeMap or anything related directly to using the Map interface, how do I extract the key set of the map into a list and apply a sorting algorithm on it (like quick sort, for example) and have an output of those sorted keys with their assigned value? (I can write the sorting algorithm by myself so it's not a concern). The keys and values are unique.

I can change the method to use an array list instead of a map and directly apply the sorting algorithm on in. I also know there are various great ways to do this sorting revolving around using the Map interface, but this is just for the sake of practicing and I'm curious to know how do I implement something like that.

My item list look like this (I use the second data row 'upc14' as key and the final data row 'name' as value):

grp_id,upc14,upc12,brand,name
1,00035200264013,035200264013,Riceland,Riceland American Jazmine Rice
2,00011111065925,011111065925,Caress,Caress Velvet Bliss Ultra Silkening Beauty Bar - 6 Ct
3,00023923330139,023923330139,Earth&#39;s Best,Earth&#39;s Best Organic Fruit Yogurt Smoothie Mixed Berry
4,00208528800007,208528800007,Boar&#39;s Head,Boar&#39;s Head Sliced White American Cheese - 120 Ct
5,00759283100036,759283100036,Back To Nature,Back To Nature Gluten Free White Cheddar Rice Thin Crackers
6,00074170388732,074170388732,Sally Hansen,Sally Hansen Nail Color Magnetic 903 Silver Elements
7,00070177154004,070177154004,Twinings Of London,Twinings Of London Classics Lady Grey Tea - 20 Ct
8,00051600080015,051600080015,Lea &amp; Perrins,Lea &amp; Perrins Marinade In-a-bag Cracked Peppercorn
9,00019600923015,019600923015,Van De Kamp&#39;s,Van De Kamp&#39;s Fillets Beer Battered - 10 Ct
10,00688267141676,688267141676,Ahold,Ahold Cocoa Almonds
public class ReadFile {
// File reading stuffs
private static Map&lt;Long,String&gt; readFromCSV() {
Map&lt;Long,String&gt; map = new LinkedHashMap&lt;&gt;();
try {
BufferedReader reader = new BufferedReader(new FileReader(&quot;Grocery_UPC_Database.csv&quot;));
reader.readLine();
String line = reader.readLine();
while (line != null) {
String[] attributes = line.split(&quot;,&quot;);
for(int i = 1; i &lt; attributes.length; i++) {
map.put(Long.parseLong(attributes[1]), attributes[4]);
}
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
private static void createFile(Map&lt;Long,String&gt; map) {
PrintWriter out = null;
try {
out = new PrintWriter(&quot;output.txt&quot;);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (Map.Entry&lt;Long,String&gt; entry : map.entrySet()) {
assert out != null;
out.println(entry.getValue());
}
assert out != null;
out.close();
}
public static void main(String[] args) {
Map&lt;Long,String&gt; map = readFromCSV();
createFile(map);
}
}

答案1

得分: 2

> 如何从地图中提取键集...

调用 keySet()

> ... 转到列表中 ...

将键复制到 List 中,使用专为此目的设计的 ArrayList 构造函数:

List<Long> keyList = new ArrayList<>(map.keySet());

> ... 并在其上应用排序算法(例如快速排序)...

调用 sort() (Java 8+)Collections.sort(),使用实现所需排序的 Comparator,例如:

keyList.sort((a, b) -> Long.compare(b, a)/*sort descending*/);

> ... 并且获得这些已排序键及其分配的值的输出?

迭代列表并从地图中打印值,例如:

for (Long key : keyList) {
System.out.println(key + " = " + map.get(key));
}
英文:

> how do I extract the key set of the map ...

Call keySet().

> ... into a list ...

Copy the keys into a List using the ArrayList constructor made for the purpose:

List&lt;Long&gt; keyList = new ArrayList&lt;&gt;(map.keySet());

> ... and apply a sorting algorithm on it (like quick sort, for example) ...

Call sort() (Java 8+) or Collections.sort(), with a Comparator that implements the desired ordering, e.g.

keyList.sort((a, b) -&gt; Long.compare(b, a)/*sort descending*/);

> ... and have an output of those sorted keys with their assigned value?

Iterate the list and print the values from the map, e.g.

for (Long key : keyList) {
System.out.println(key + &quot; = &quot; + map.get(key));
}

答案2

得分: 1

如果您使用的是Java8,您可以使用流(streams)通过compareByKey()进行排序。

Map sortedMap = map.entrySet().stream().sorted(comparingByKey())
    .collect(toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2), LinkedHashMap::new));
英文:

If you are using Java8, you can use streams to sort using compareByKey().

Map sortedMap = map.entrySet().stream().sorted(comparingByKey())
.collect(toMap(e -&gt; e.getKey(), e -&gt; e.getValue(), (e1, e2) -&gt; e2), LinkedHashMap::new));

huangapple
  • 本文由 发表于 2020年9月26日 04:15:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64070823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定