【发布时间】:2013-03-08 09:00:52
【问题描述】:
我有一个包含多个复杂 for 和 if 语句的方法。资源使用并不重要,因为该应用仍在开发中,但我想知道是否有某种方法可以优化它,因为它看起来非常沉重。
这一切都归结为:如果我有多个映射的Object,有没有办法检查我的对象的一个(已知)字段中的值,如果满足该值,则使用相同的值,不会在我的地图上重复太多次。
这是代码
private Map<Integer, Reservation> CreerMapFax(HttpServletRequest request, HttpSession session)
{
// Get the "keys" parameter array from the request
// and makes an array of integers
String[] strKeys = request.getParameterValues("keys");
Integer[] intKeys = new Integer[strKeys.length];
for (int i = 0; i < strKeys.length; i++)
intKeys[i] = Integer.parseInt(strKeys[i]);
// Creates Map (1) of the selected bookings that need to be faxed,
// gets Map (2) of all registered bookings within session
// and fill (1) with data from (2)
// by using the keys stored in the array
boolean mail = true;
Map<Integer, Booking> mapFax = new HashMap<Integer, Booking>();
Map<Integer, Booking> bookings=
(HashMap<Integer, Booking>) session.getAttribute(SESSION_BOOKINGS);
for (int i = 0; i < intKeys.length; i++)
{
Booking booking = bookingss.get(intKeys[i]);
if (!booking.getMailing())
mail = false;
// Some updating done here on "booking"
...
// Overwrite old map values with new ones
bookings.put(intKeys[i], booking);
mapFax.put(intKeys[i], booking);
}
// mail == false whenever at least one of the booking
// stored in the map had their getMailing() method return false
if (!mail)
{
for (int j = 0; j < intKeys.length; j++)
{
// Updates AGAIN !
Booking booking = mapFax.get(intKeys[j]);
booking.setMailing(false);
mapFax.put(intKeys[j], booking);
reservations.put(intKeys[j], booking);
}
}
session.setAttribute(SESSION_BOOKINGS, BOOKINGS);
return mapFax;
}
基本上,这样做的目的(除了更新 Booking 对象的其他字段并返回 mapFax 映射以进行进一步处理)是将邮件字段设置为 false 中的每个对象mapFax 如果至少有一个值设置为 false。
如果for(){if(){}} 后跟if(){for(){}} 我想知道是否有某种方法可以使其更高效和可读?
【问题讨论】:
-
您发布的代码似乎缺少重要部分。你只有一个
for...if组合,没有if...for,而且你在if(设置mail=false)中所做的事情在任何地方都不会使用。 -
听起来像是 codereview.stackexchange.com 的问题。
-
如果你必须循环遍历对象映射来设置字段,听起来你的 Java 对象没有被规范化。
标签: java loops optimization