You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中如何筛选并打印元组列表中长度为4的字符串?

解决Scala Tuple列表过滤问题

Hey there! Since you're new to Scala, let's walk through how to solve this problem clearly. You have a list of Tuple[Int, String] and want to print all elements where the string has a length of 4—here's how to do it step by step:

Step 1: Define your tuple list

First, let's make sure we have your list correctly defined (Scala uses List for collections of elements, so we'll adjust your syntax slightly):

val tupleList = List((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))

Step 2: Filter and print the elements

Scala's collections have super handy methods for this kind of task. We'll use filter to keep only the tuples where the string (second element of the tuple) has length 4, then print the results.

Option 1: Concise Scala-style syntax

This uses underscore shorthand, which is common in Scala once you get comfortable with it:

// Filter elements where the string's length is 4, then print each one
tupleList.filter(_._2.length == 4).foreach(println)

Option 2: Explicit syntax (easier for beginners)

If the shorthand feels confusing at first, you can write it out more clearly to see exactly what's happening:

tupleList.filter { tuple =>
  // Check if the second element of the tuple has length 4
  tuple._2.length == 4
}.foreach { element =>
  // Print each matching element
  println(element)
}

What this does:

  • filter: Iterates through every tuple in the list and keeps only those that meet our condition (tuple._2.length == 4—_2 refers to the second element of the tuple, which is your string).
  • foreach(println): Takes each filtered element and prints it to the console.

The output you'll get:

(2,beta)
(4,zeta)

内容的提问来源于stack exchange,提问作者iamdeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:15:29