基于Scala中的模式匹配,我如何在地图中找到一个键 [英] how can i find a key in a map based on a pattern matching in scala

查看:98
本文介绍了基于Scala中的模式匹配,我如何在地图中找到一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在地图上找到一个类似于特定文字的键。我应该使用for循环还是有更优雅的方式?

I want to find a key in a map that is similar to a specific text. should I use for loop or is there a more elegant way?

推荐答案

你的问题的直接翻译是 map.keys.find(_。matches(pattern))给出地图,获取它们的键并找到与正则表达式模式匹配的第一个键。

The direct translation of your question is map.keys.find(_.matches(pattern)) which given a map, gets they keys and finds the first key that matches the regexp pattern.

val map = Map("abc" -> 1, "aaa" -> 2, "cba" -> 3)
map.keys.find(_.matches("abc.*"))
// Some(abc)
map.keys.find(_.matches("zyx"))
// None

如果您不想扫描所有的键,循环可能会有效。

A loop may be counter productive if you don't want to scan all keys.

这篇关于基于Scala中的模式匹配,我如何在地图中找到一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆