gpt4 book ai didi

java - 维护java中项目的顺序

转载 作者:行者123 更新时间:2023-12-01 19:22:36 24 4
gpt4 key购买 nike

执行以下操作的最佳方法是什么(确保 List 中的项目与 ListTwo 中的项目遵循相同的顺序):

List 

harry~20
marry~22
peter~40
jerry~33
janice~20

ListTwo

harry
marry
peter
janice

现在结果应该是这样的

列表三

harry
marry
peter
janice
jerry

一步一步:

对于列表中的每个项目:

  1. compare first part of the item to item in ListTwo

  2. if they are equal add it to ListThree

  3. if item exist in List but not in ListTwo dont do anything yet save it somewhere

continue from step 1

  1. you are at the end of the List add the item(s) you skipped before in step 3

我知道这么多(实际上我不知道,我想我知道),我确信有更好的方法来做到这一点

为什么我被否决了,我错过了什么吗?

最佳答案

如果您颠倒角色(按顺序将键存储在 ArrayList 中)和 SortedMap (例如 TreeMap)中的键值映射,可能会更容易,或ConcurrentSkipListMap。排序映射的比较器可以使用List.indexOf作为元素比较的基础。

通过这种安排,映射定义了键/值映射,这对于映射来说是很自然的,并且列表保持了所需的顺序,这对于列表来说是很自然的。

或者,使用常规映射,而不是排序映射,并在列表上使用迭代,并从映射中获取值。例如

ArrayList keysList;
Map keyValues;
for(String key: keysList) {
String value = keyValues.get(key);
}

编辑:Commons Collection 有 SetUniqueList - 像集合一样确保唯一性的列表。它还具有各种类型的 OrderedMap,特别是 ListOrderedMap按列表顺序维护键/值映射。有关泛型支持,请参阅 commons collections with generics .

关于java - 维护java中项目的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3294831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com