我有一个方法,有几个错综复杂的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
中的每个对象。
如果for(){if(){}}
后跟if(){for(){}}
,我想知道是否有某种方法可以使它更加高效和可读?
您的发布代码似乎缺少重要部分。你只有一个'for ... if'组合,没有'if ... for',并且你在'if'(set'mail = false')中做的事不会在任何地方使用。 – 2013-03-19 15:41:45
听起来像是codereview.stackexchange.com的问题。 – 2013-03-19 15:44:23
如果您必须循环遍历对象映射来设置字段,则您的Java对象的声音没有标准化。 – 2013-03-19 15:48:53