我有对象列表.我需要做分页.
输入参数是每页和页码的最大对象数.
例如输入每页list = ("a", "b", "c", "d", "e", "f")
的最大数量是2页数是2结果=("c","d")
有没有现成的类(libs)来做这个?例如Apache项目等.
我正在使用这样的代码来处理由多行组成的文件:
BufferedReader reader = ...
reader.lines().forEach(Same common Action)
Run Code Online (Sandbox Code Playgroud)
只要每条线都需要以相同的方式处理,这种方法就可以正常工作.但有时可能会有几种不同的行为.
例如,假设第一行是标题,其他行是内容.对于我想要执行的第一行Action1,以及我想要的其他行Action2.
在Java 7风格中,我会做这样的事情:
String line;
boolean first = true;
while ( (line = reader.readLine()) != null) {
if (first) {
action1(line);
first = false;
} else {
action2(line);
}
}
Run Code Online (Sandbox Code Playgroud)
但那是复杂而丑陋的,根本就没有使用流.如何使用Java 8流以惯用的方式做到这一点?
Java 8提供了Optional类.
之前(Java 7):
Order order = orderBean.getOrder(id);
if (order != null) {
order.setStatus(true);
pm.persist(order);
} else {
logger.warning("Order is null");
}
Run Code Online (Sandbox Code Playgroud)
所以在Java 8风格上:
Optional<Order> optional = Optional.ofNullable(orderBean.getOrder(id));
optional.ifPresent( s -> {
s.setStatus(true);
pm.persist(s);
//Can we return from method in this place (not from lambda) ???
});
//So if return take place above, we can avoid if (!optional.isPresent) check
if (!optional.isPresent) {
logger.warning("Order is null");
}
Run Code Online (Sandbox Code Playgroud)
Optional在这种情况下使用是否正确?任何人都可以在Java 8风格中提出更方便的方法吗?
我有两个类非常相似的类
A类:
String getString(Set<Map.Entry<String, List<String>>> headers) {
return headers.stream().map(h -> String.join(": ", h.getKey(), h.getValue().stream().
collect(Collectors.joining(", ")))).collect(Collectors.joining(System.lineSeparator()));
}
Run Code Online (Sandbox Code Playgroud)
B级
String getString(Set<Map.Entry<String, Collection<String>>> headers) {
return headers.stream().map(h -> String.join(": ", h.getKey(), h.getValue().stream().
collect(Collectors.joining(", ")))).collect(Collectors.joining(System.lineSeparator()));
}
Run Code Online (Sandbox Code Playgroud)
方法参数泛型类型的唯一区别:
Set<Map.Entry<String, List<String>>> headers
Set<Map.Entry<String, Collection<String>>> headers
Run Code Online (Sandbox Code Playgroud)
我不会编码重复.并寻找方式haw我可以在一个重构这两个方法.
我正在尝试使用不同的通用通配符组合编写代码(?super或?extends).但失败了.例如:
Set<Map.Entry<String, ? extends Collection<String>>>
Run Code Online (Sandbox Code Playgroud)
你能不能支持我如何重构这个泛型的想法.谢谢