好吧,所以我得到了一个按键排序的树图。键是一个整数,值是一个字符串。我正在尝试制作将按值显示前3个元素的Toast。他们已经被排名了,我只想在烤面包上显示他们的名字。我认为这很容易,但是我尝试了很多失败的东西,所以我在这里抓住稻草。这是它的样子。
TreeMap<Integer, String> sorted = new TreeMap<>(courses);
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, ,duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
我曾考虑过要使用for循环来获取前3个元素,但是我还需要在元素周围拍一些漂亮的文字,所以我没主意了,可能是因为这是凌晨3点,而且我很累。任何帮助表示赞赏。谢谢。
要从地图中获取前三个值,可以使用:
sorted.entrySet().stream() // stream the entries from the map
.limit(3) // only take the first three
.map(Map.Entry::getValue) // get the value from the entry
.collect(Collectors.joining(", ")); // collect them in a comma-delimited list
默认情况下,TreeMap将对条目从最低到最高进行排序。要将它们从最高到最低排序,请使用合适的Comparator创建TreeMap:
// creating a TreeMap with a Comparator that compares integers in reverse order
TreeMap<Integer, String> sorted = new TreeMap<>((a, b) -> Integer.compare(b, a));