Java的钥匙值对有序集合
我有一个带有列的2D表: Language 和熟练度,我需要用输入来填充。
我已经创建了一个方法:
public void typeLanguages(@NotNull List<String> languages,
@NotNull List<SkillLevel> skillLevels) {
if(languages.size() != skillLevels.size()) { throw new IllegalArgumentException(); }
IntStream.range(0, skillLevels.size()).forEach(i -> {
typeAndConfirm(languagesFld.get(i), languages.get(i));
typeAndConfirm(skillFld.get(i), skillLevels.get(i).getLangSkill());
});
}
intstream
已被使用,因此 i
-th language-skilllevel 对插入 i -th Row。
SkillLevel
是一个枚举,它实现 getlangskill()
方法,返回的方法是字符串的四个熟练度级别之一
,但是,用户可以提供不同尺寸列表的风险( 虽然受保护),或者他们可以混合订单并给自己错误的熟练程度得分。
afaik在爪哇没有任何元素。我尝试使用MAP,但看不到任何可以让我使用 i
的方法 - 地图的元素。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要滥用
这两个数据: Language 和 Level 不要单独具有任何值,只有当您拥有它们两者都是有用的。这意味着他们必须构成一个对象。尝试使用
MAP
的尝试只是为了描述这两个属性之间的关系,这将是滥用收集的内容,这将导致无可限制的代码。因此,您可以定义a 记录 (或a class 如果您希望它是可变的或更早使用版本比Java 16 )将这两个属性组合到一个对象中:
用它而不是
list&lt; string&gt;
andlist&lt; skill&lt; skill&gt;
您将处理一个list&lt; languagelevel&gt;
。如果您想对列表中的对象进行排序,并且只有一种特定的分类方式在您的应用程序中有意义 - 所谓的自然顺序,那么您可以制作
languagelevel 实施可比性
接口。但是,如果在您的域模型中,这些对没有自然顺序,并且它们的分类可能会有所不同,具体取决于
比较>比较>比较
接口。您可以定义多个比较器以促进不同的分类方式。例如:
Don't misuse Collections
The two pieces of data: language and level don't a have any value separately, only when you have them both they are useful. That means they have to constitute an object. An attempt to utilize a
Map
just for the purpose of describing the relationship between the two properties would be an abuse of collection, which would result in unmaintainable code.So instead of maintaining the two separate lists, which makes your code brittle, you can define a record (or a class if you want it to be mutable or using a version earlier than Java 16) that will combine both properties into a single object:
With that instead of
List<String>
andList<SkillLevel>
you will deal with aList<LanguageLevel>
.In case if you would want to sort the objects in a list and there's only one particular way of sorting that makes sense in your application - so called natural order, then you can make
LanguageLevel
implementComparable
interface.But if in your domain model, these pairs have no natural order, and they might be sorted differently depending on a situation that have a look at the
Comparator
interface.You can define multiple comparators to facilitate different ways of sorting. For example:
要么:
navigableMap
例如treemap
可比较
的地图方法:
键值对将通过字符串键的自然顺序自动排序。
Either:
NavigableMap
such asTreeMap
Comparable
For the map approach:
The key-value pairs will be automatically sorted by the natural order of the string keys.