编辑:我的列表是按来自数据库的顺序排序 我有一个具有类People对象的ArrayList.人们有两个属性:ssn和terminationReason.所以我的列表看起来像这样
ArrayList:
ssn TerminatinoReason
123456789 Reason1
123456789 Reason2
123456789 Reason3
568956899 Reason2
000000001 Reason3
000000001 Reason2
Run Code Online (Sandbox Code Playgroud)
我想更改此列表,以便没有重复项,并且终止原因由逗号分隔.
所以上面的列表将成为
New ArrayList:
ssn TerminatinoReason
123456789 Reason1, Reason2, Reason3
568956899 Reason2
000000001 Reason3, Reason2
Run Code Online (Sandbox Code Playgroud)
我有一些东西在我循环原始列表并匹配ssn,但它似乎不起作用.
有人可以帮忙吗?
我使用的代码是:
String ssn = "";
Iterator it = results.iterator();
ArrayList newList = new ArrayList();
People ob;
while (it.hasNext())
{
ob = (People) it.next();
if (ssn.equalsIgnoreCase(""))
{
newList.add(ob);
ssn = ob.getSSN();
}
else if (ssn.equalsIgnoreCase(ob.getSSN()))
{
//should I get last object from new list and append this termination reason?
ob.getTerminationReason()
}
}
Run Code Online (Sandbox Code Playgroud)
对我来说,这似乎是一个使用a的好例子Multimap,它允许为单个密钥存储多个值.
这可能意味着可能必须分别取出Person对象ssn和terminationReason字段作为键和值.(这些字段将被假定为String.)
基本上,它可以使用如下:
Multimap<String, String> m = HashMultimap.create();
// In reality, the following would probably be iterating over the
// Person objects returned from the database, and calling the
// getSSN and getTerminationReasons methods.
m.put("0000001", "Reason1");
m.put("0000001", "Reason2");
m.put("0000001", "Reason3");
m.put("0000002", "Reason1");
m.put("0000002", "Reason2");
m.put("0000002", "Reason3");
for (String ssn : m.keySet())
{
// For each SSN, the termination reasons can be retrieved.
Collection<String> termReasonsList = m.get(ssn);
// Do something with the list of reasons.
}
Run Code Online (Sandbox Code Playgroud)
如有必要,Collection可以生成以逗号分隔的a列表:
StringBuilder sb = new StringBuilder();
for (String reason : termReasonsList)
{
sb.append(reason);
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
String commaSepList = sb.toString();
Run Code Online (Sandbox Code Playgroud)
这可以再次设置到该terminationReason领域.
正如Jonik在评论中提到的那样,另一种方法是使用Apache Commons中的StringUtils.join方法Lang可以用来创建逗号分隔列表.
还应注意,Multimap没有指定实现是否应该允许重复的键/值对,因此应该查看Multimap要使用的类型.
在此示例中,这HashMultimap是一个不错的选择,因为它不允许重复的键/值对.这将自动消除为某个特定人员提供的任何重复原因.
| 归档时间: |
|
| 查看次数: |
4274 次 |
| 最近记录: |