java map.entry new_java – 如何将一个Map Entry添加到ArrayList?

我正在创建Map Entry键值对的ArrayList.这样我就可以存储大量单个单词(作为键)并保存它们的总次数(作为值).

我需要能够按值对ArrayList进行排序,以便我可以按其值排序单词.

我有两个问题:

>我不知道将映射条目添加到ArrayList的语法

>我不确定如何对ArrayList进行排序

任何帮助非常感谢!

protected void addKeywords(Status status) {

// get tweet

String str = status.getText();

// split into an array remove punctuation and make lower case

String[] splited = str.replaceAll("[^a-zA-Z ]", "").toLowerCase()

.split("\\s+");

// vars used in loop

String thisStr;

int wordTot;

Entry newEntry = null;

for (int i = 0; i < splited.length; i++) {

// get word from array

thisStr = splited[i].toLowerCase();

thisStr = "hi";

// if this is the first word to be added

if (mapList.size() == 0) {

//this is the syntax that I don't know!

newEntry.key = theStr;

newEntry.value = 1;

mapList.add(newEntry);

} else {

boolean alreadyExists = false;

//iterate through mapList

for (Entry entry : mapList) {

// already exists

if (entry.getKey() == thisStr) {

wordTot = entry.getValue();

//increment the value

wordTot++;

entry.setValue(wordTot);

break;

}

}

//if we have reached here the value must not be in the arraylist so add it

//again - this is the syntax that I don't know!

newEntry.key = theStr;

newEntry.value = 1;

mapList.add(newEntry);

}

}

}

-EDIT – 工作代码

嗨,我添加了新的代码,将地图条目添加到ArrayList,这很有用.

我还更新了我的排序代码,这也很有效:

private void sortMap() {

Collections.sort(mapList, new Comparator>() {

@Override

public int compare(Map.Entry o1, Map.Entry o2) {

if (o1.getValue()>o2.getValue()){

return 1;

}else if (o1.getValue()

return -1;

}else{

return 0;

}

}

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值