I have a string sequence and a HashMap
.I need to sort my hashmap according to the sequence.If the hashmap contains strings which is present in the sequence,those strings should sort according to the sequence and print.
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());
}
The output I'm getting here is
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
My Expected output:
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
In my code I'm storing the elements which are not equal to sequence into an arraylist and printing that.But I can't design the loop properly which will add only the remaining elements which does not contains strings in sequence.Somebody help me on this.Thanks
EDIT:For this same problem I tried to write a comparator. But it not works
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;
}
};