【发布时间】:2013-09-10 12:57:51
【问题描述】:
我有一个字符串序列和一个HashMap。我需要根据序列对我的hashmap进行排序。如果hashmap包含序列中存在的字符串,这些字符串应该根据序列排序并打印。
String sequence="People,Object,Environment,Message,Service";
HashMap<String, String> lhm = new HashMap<String, String>();
List<String> list=new ArrayList<String>();
lhm.put("Objectabc", "biu");
lhm.put("Message someText", "nuios");
lhm.put("Servicexyxyx", "sdfe");
lhm.put("People bcda", "dfdfh");
lhm.put("Environment qwer", "qwe");
lhm.put("Other", "names");
lhm.put("Elements", "ioup");
lhm.put("Rand", "uiy");
// Get a set of the entries
Set<Entry<String, String>> set = lhm.entrySet();
String[] resultSequence=sequence.split(",");
for(int j=0;j<resultSequence.length;j++)
{
Iterator<Entry<String, String>> iter = set.iterator();
while(iter.hasNext()) {
Map.Entry me = (Map.Entry)iter.next();
String res=(String) me.getKey();
if(res.contains(resultSequence[j]))
{
System.out.println("values according with the sequence is "+res);
}
if(!res.contains(resultSequence[j]))
{
list.add(res);
// System.out.println("values not according with the sequence is "+res);
}
}
}
List<String> list2=new ArrayList<String>(new LinkedHashSet<String>(list));
Iterator<String> iterlist2=list2.iterator();
while(iterlist2.hasNext())
{
System.out.println("non equal elements are "+iterlist2.next());
}
我在这里得到的输出是
values according with the sequence is People bcda
values according with the sequence is Objectabc
values according with the sequence is Environment qwer
values according with the sequence is Message someText
values according with the sequence is Servicexyxyx
non equal elements are Elements
non equal elements are Other
non equal elements are Servicexyxyx
non equal elements are Objectabc
non equal elements are Message someText
non equal elements are Rand
non equal elements are Environment qwer
non equal elements are People bcda
我的预期输出:
values according with the sequence is People bcda
values according with the sequence is Objectabc
values according with the sequence is Environment qwer
values according with the sequence is Message someText
values according with the sequence is Servicexyxyx
non equal elements are Elements
non equal elements are Other
non equal elements are Rand
在我的代码中,我将不等于序列的元素存储到数组列表中并打印出来。但我无法正确设计循环,它将仅添加不包含序列中字符串的剩余元素。有人帮我解决这个问题。谢谢
编辑:对于同样的问题,我尝试编写一个比较器。但它不起作用
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String key1, String key2) {
int returned = sequence.indexOf(key1) - sequence.indexOf(key2);
if (returned == 0 && !key1.contains(key2))
returned = -1;
return returned;
}
};
【问题讨论】:
-
为什么要将
new LinkedHashSet<String>(list)转换回列表只是为了迭代?迭代器应该保留顺序,毕竟它是一个 linked 哈希集。 :) -
@Thomas 我试图从我的列表中删除重复的值。所以这样做了
-
“我需要根据该哈希图对哈希图进行排序”是什么意思?
-
@arjacsoh 编辑了我的问题
-
查看此处进行排序 LinkedHashMap stackoverflow.com/questions/12184378/sorting-linkedhashmap