About the Lambda FAQ(关于Lambda的问答集)

本文介绍了Java中引入Lambda表达式的背景及进展。随着Java8的即将发布,Lambda表达式将成为Java编程的重要特性之一。文章还提到了这将对集合操作产生的影响,并预告了《Java泛型与集合》一书的新版更新。

About the Lambda FAQ(关于Lambda的问答集)

原文地址:http://www.lambdafaq.org/

本文仅供学习和交流使用,如果您发现我已经侵犯到原作者的版权,请邮件我ttchgm@gmail.com。以便我及时删除和处理。如果翻译有错误或者交流可以随时mail我。或者在sina微博 @天天吃好,私信与我。 本文拒绝任何形式转载。

关于如何在java中引入lambda表达式的长期讨论中(aka closures),我们接近了一个重要的时刻:lambdas的实现和虚函数扩展是计划在2012年1月底完成的特性,紧随其后9月份会在发布JDK8中正式加入其中。这是在Java 5开始后的做的最大的变化,发布日期离我们并不遥远。

aka closures的完整叙述,一个闭包是一个lambda表达式对,在表达式对内的环境绑定所有自由变量到一个值。在Java中,Lambda表达式将实现的意义为闭包,所以两个关系可以使用在区间内交换使用。

关于aka closures可以参考这个链接 http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html

我开始思考关于这些新特性,所以Phil Wadler 和我认为应该有一本新版本的<<Java Generics and Collections>>的书。这里特别重要,尤其重要的是关于集合,我们需要做出大量的修改保持当前这本书中的例子适应lambda表达式以及lambda表达式更广泛的使用。

新的特性并不是在第一时间都能消化的,所以这个FAQ有益于让你在我的劳动成果中学习到他们。我希望她对你有帮助,无论你是否已经熟悉了lambda表达式或者第一时间早已接触到了lambda表达式。我高兴接受任何您的评论和贡献。

import lunardate as ld from datetime import date, timedelta import sqlite3 from threading import Timer import json import requests # 1.多历法显示 def get_lunar_date(gregorian_date): """返回对应公历日期的农历表示""" lunar = ld.LunarDate.fromSolarDate( gregorian_date.year, gregorian_date.month, gregorian_date.day ) return f"{lunar.year}年{lunar.month}月{lunar.day}日" def generate_solar_terms(year): """生成某年的二十四节气表""" solar_terms = [ ("立春", "02-03"), ("雨水", "02-18"), ("惊蛰", "03-05"), ("春分", "03-20"), # ... 完整列表省略 ... ] result = [] for term, day_str in solar_terms: month, day = map(int, day_str.split("-")) dt = date(year, month, day) result.append((term, dt)) return result # 2.节假日管理 fixed_holidays = { (1, 1): "元旦", (5, 1): "劳动节", # 添加更多固定节日... } def is_holiday(date_obj): """判断某个日期是否为法定节假日""" key = (date_obj.month, date_obj.day) if key in fixed_holidays: return fixed_holidays[key] return None # 3.日程规划与提醒 conn = sqlite3.connect(":memory:") cursor = conn.cursor() # 创建日程表 cursor.execute(""" CREATE TABLE IF NOT EXISTS schedules ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, start_time DATETIME NOT NULL, remind_before INTEGER DEFAULT 0 ); """) def add_schedule(title, start_time, remind_before=0): cursor.execute("INSERT INTO schedules (title, start_time, remind_before) VALUES (?, ?, ?)", (title, start_time, remind_before)) conn.commit() def send_reminder(schedule_id): print(f"Reminder: Schedule {schedule_id} is about to start!") def set_timer_for_schedule(): cursor.execute( "SELECT id, start_time, remind_before FROM schedules WHERE strftime('%s', start_time) > strftime('%s', 'now')") rows = cursor.fetchall() now_timestamp = int(date.today().timestamp()) for row in rows: schedule_id, start_time, remind_before = row time_diff = int(start_time.timestamp()) - now_timestamp - remind_before * 60 timer = Timer(time_diff, lambda sid=schedule_id: send_reminder(sid)) timer.start() # 4.黄历宜忌 def load_horoscopes(file_path='horoscopes.json'): try: with open(file_path, 'r', encoding='utf-8') as file: data = json.load(file) return data except FileNotFoundError: print(f"Error: The file '{file_path}' was not found.") # 提供一个默认的数据结构作为回退选项 return {"default": "No horoscope data available"} # 调用函数 horoscopes_data = load_horoscopes() print(horoscopes_data) # 5.天气服务 API_KEY = "your_openweathermap_api_key" def fetch_weather(city_name): url = f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&units=metric&lang=zh_cn&appid={API_KEY}" response = requests.get(url).json() if response["cod"] != 200: raise ValueError(response["message"]) weather_info = { "description": response["weather"][0]["description"], "temperature": response["main"]["temp"] } return weather_info # 6.综合 if __name__ == "__main__": today = date.today() print(f"Today's Date: {today}") print(f"Lunar Date: {get_lunar_date(today)}") holiday = is_holiday(today) if holiday: print(f"Holiday Today: {holiday}") try: city = input("Enter your city name: ") weather = fetch_weather(city) print(f"Weather in {city}: {weather['description']}, Temp: {weather['temperature']}°C") except Exception as e: print(f"Error fetching weather: {e}") daily_horoscope = load_horoscopes() print(f"Suitable Activities: {daily_horoscope['suitable']}") print(f"Avoid These: {daily_horoscope['taboo']}") 代码如上,运行时输入和报错如下: Error: The file 'horoscopes.json' was not found. {'default': 'No horoscope data available'} Today's Date: 2025-05-26 Lunar Date: 2025年4月29日 Enter your city name: 重庆 Error fetching weather: Invalid API key. Please see https://openweathermap.org/faq#error401 for more info. Traceback (most recent call last): File "C:\Users\Lenovo\PycharmProjects\untitled5\万年历\多历法显示.py", line 140, in <module> print(f"Suitable Activities: {daily_horoscope['suitable']}") KeyError: 'suitable' Error: The file 'horoscopes.json' was not found.请分析
05-27
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值