我正试图在playFramework2.2中的scala模板中循环映射。这是它的代码:
<ol>
@for(((key, value), currentIndex) <- m.myMap.zipWithIndex) {
<li>@key - @value - @currentIndex</li>
}
</ol>
java:中的映射声明
Map myMap = new HashMap<String, Integer>();
scala:中的映射声明
meters: List[intranet.controllers.Index.Meter]
我已经用java方法对该映射(按值)进行了排序,如下所示:
public static Map sort(Map unsortMap, Order order) {
List list = new LinkedList(unsortMap.entrySet());
comparator = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
}
}
Collections.sort(list, comparator);
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
不幸的是,我的问题是,我用zipWithIndex
方法迭代映射,我失去了顺序。
以下是当前结果:
Key - Value - Index
WA - 41 - 4
BA - 66 - 0
BM - 52 - 2
DP - 0 - 6
JTM - 0 - 7
TN - 59 - 1
WP - 46 - 3
SM - 0 - 5
正如你所看到的,它没有被订购,但它应该是这样的:
Key - Value - Index
BA - 66 - 0
TN - 59 - 1
BM - 52 - 2
WP - 46 - 3
WA - 41 - 4
SM - 0 - 5
DP - 0 - 6
JTM - 0 - 7
所以问题是:
- 如何迭代具有原始顺序索引的映射
我想明白了第一个问题。这是工作循环代码:
@for(((key, value), currentIndex) <- m.lastMonthRanking.view.zipWithIndex) {
<li>
<span @if(session().get("email").equals(key)){ class="label label-info" style="font-size: 100%; display: grid"}>@key
<span class="badge">@value</span>
</span>
</li>
}
- 如何访问当前迭代元素之后/之前的下一个/上一个元素
编辑
我有一个映射,其中键是@userName
(String),@value
是(Integer)。我想打印@value
订购的列表<ol><li>@userName (@value)</li></ol>
。如果值在许多用户中重复,我想用其他方式打印这些元素,所以我必须知道列表中的下一个/上一个元素是否具有相同的值。通常在带有列表的java中,我会做这样的事情:
for (int i = 0; i < CrunchifyList.size(); i++) {
System.out.println(CrunchifyList.get(i-1) + " is previous element");
System.out.println(CrunchifyList.get(i) + " is current element");
System.out.println(CrunchifyList.get(i+1) + " is next element");
}
但现在我需要用scala和map来做这件事。请帮助
对于第一个问题,您应该使用一个维护插入顺序的映射。一个例子是scala.collection.immutable.ListMap
。
@ import scala.collection.immutable.{HashMap, ListMap}
import scala.collection.immutable.{HashMap, ListMap}
@ val l = 1 to 5
l: collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)
@ val hm = HashMap(l.zipWithIndex: _*)
hm: HashMap[Int, Int] = Map(5 -> 4, 1 -> 0, 2 -> 1, 3 -> 2, 4 -> 3)
@ val lm = ListMap(l.zipWithIndex: _*)
lm: ListMap[Int, Int] = Map(1 -> 0, 2 -> 1, 3 -> 2, 4 -> 3, 5 -> 4)
@for(((键,值),currentIndex)<-m.myMap.迭代器.zip WithIndex){