将映射和集合一起用作Java中的数据结构

时间:2015-01-09 00:24:25

标签: java set maps

我有一个程序可以记录轨道以及播放它的次数并将其输出...简单..但我无法按降序进行计数。我的第二个问题是,如果有多个轨道具有相同的计数,它应该查看轨道的名称并按字母顺序打印它。我到达了可以打印所有内容的点,因为它应该没有顺序但是,因为我正在使用地图,每当我使用列表对其进行排序时,它都会按升序排序。

这是我的代码和输出

import java.util.*;
import java.io.*;
import java.lang.*;
import lab.itunes.*;

public class Music     {
public static void main(String[] args) throws Exception     {
    try  {
    Scanner input = new Scanner(System.in);
    PrintStream output = new PrintStream(System.out);
    Map<String,Integer> mapp = new HashMap<String,Integer>();
    List<Integer> list1 = new ArrayList<Integer>();
    output.print("Enter the name of the iTunes library XML file:");
    String entry = input.nextLine();
    Scanner fileInput = new Scanner(new File(entry));
    Library music = new Library(entry); // this class was given to us.
    Iterator<Track> itr = music.iterator(); // scan through it
    while (itr.hasNext())
    {
        Track token = itr.next(); // get the tracks
        mapp.put(token.getName(),token.getPlayCount()); // fill our map 
         list1.add(token.getPlayCount()); // fill our list too 
    }
    for(Map.Entry<String,Integer> testo : mapp.entrySet())  {
        String keys = testo.getKey(); 
        Integer values = testo.getValue();
        output.printf("%d\t%s%n",values,keys); // printing the keys and values in random order.
    }
    } catch (FileNotFoundException E)   {
        System.out.print("That file does not exist");
    }
}

}

输出是这个..

Enter the name of the iTunes library XML file:library.txt
87  Hotel California
54  Like a Rolling Stone
19  Billie Jean
75  Respect
26  Imagine
19  In the Ghetto
74  Macarena
27  Hey Jude
67  I Gotta Feeling
99  The Twist
你可以给我一个提示吗?我工作了至少4个小时才能做到这一点..谢谢

3 个答案:

答案 0 :(得分:1)

Library类是否有sort()方法?如果没有,您可以在提出music之前添加一个并在库iterator()上调用sort()。

public class Library
{
    // ... existing code ...

    public void sort()
    {
        class TrackPlayCountComparator implements Comparator<Track>
        {
            @Override
            public int compare(Track t1, Track t2) {
                int compare = t2.getPlayCount() - t1.getPlayCount();
                if (compare == 0) {
                    return t1.getName().compareTo(t2.getName());
                }
                return compare;
            }
        }
        Collections.sort(this.tracks, new TrackPlayCountComparator());
    }
}

简化您的代码:

    public static void main(String[] args) throws Exception
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the name of the iTunes library XML file: ");
        String entry = input.nextLine();
        try {
            input = new Scanner(new File(entry));
            input.close();
            Library music = new Library(entry); // this class was given to us.
            music.sort(); // sort the tracks
            PrintStream output = new PrintStream(System.out)
            for (Iterator<Track> itr = music.iterator(); itr.hasNext(); ) {
                Track track = itr.next();
                output.printf("%d\t%s%n", track.getPlayCount(), track.getName());
            }
        } catch (FileNotFoundException E) {
            System.out.print("That file does not exist");
        }
    }

答案 1 :(得分:0)

我假设您的问题是:我如何对值进行排序,而不是键?

如果是这样,这里有一些示例代码可以帮助您入门:

map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .map(entry -> entry.getKey() + "\t + entry.getValue())
    .forEach(output::println);

如果需要按相反顺序排序,则只需更改comparisonByValue比较器:

.sorted(Map.Entry.comparingByValue((val1, val2) -> val2 - val2))

按值排序,然后按字母顺序排序:

.sorted((entry1, entry2) -> entry1.getValue() == entry2.getValue() ? entry1.getKey().compareTo(entry2.getKey())) : entry2.getValue() - entry1.getValue())

通过将比较器放在一个单独的方法中,你可以使它更整洁。

private Comparator<Map.Entry<String, Integer>> songComparator() {
    return (entry1, entry2) -> {
        int difference = entry2.getValue() - entry1.getValue();
        if (difference == 0) {
            return entry1.getKey().compareTo(entry2.getKey()));
        } else {
            return difference;
        }
    }
}
然后,您将使用songComparatorsorted生成比较器。

答案 2 :(得分:0)

使用Collections.sort()按其natural order对集合进行排序,或定义Comparator并将其作为第二个参数传递。

首先,您必须更改列表以采用“跟踪”类型,并且不再需要地图:

// the list will store every track
List<Track> tracks = new ArrayList<Track>();

String entry = input.nextLine();
Scanner fileInput = new Scanner(new File(entry));
Library music = new Library(entry); // this class was given to us.
Iterator<Track> itr = music.iterator(); // scan through it
while (itr.hasNext()) {
    tracks.add(itr.next()); // add each track
}

// you can define classes anonymously:
Collections.sort(tracks, new Comparator<Track>()
{
    @Override
    public int compare(Track t1, Track t2) {
        int diff = t2.getPlayCount() - t1.getPlayCount();
        // if there is no difference in play count, return name comparison
        return (diff == 0 ? t1.getName().compareTo(t2.getName()) : diff);
    }
});

有关详细信息,请参阅Anonymous Classes