我想知道,如果流(或收集器)中已经有一个已实现的功能,它已将列表排序为值.例如,以下代码均生成按年龄分类的按性别分组的人员列表.第一个解决方案有一些开销排序(看起来有点邋)).第二个解决方案需要两次看每个人,但是以一种漂亮的方式完成工作.
首先排序然后在一个流中分组:
Map<Gender, List<Person>> sortedListsByGender = (List<Person>) roster
.stream()
.sorted(Person::compareByAge)
.collect(Collectors.groupingBy(Person::getGender));
Run Code Online (Sandbox Code Playgroud)
首先分组,然后对每个值进行排序:
Map<Gender, List<Person>> sortedListsByGender = (List<Person>) roster
.stream()
.collect(Collectors.groupingBy(Person::getGender));
sortedListsByGender.values()
.forEach(list -> Collections.sort(list, Person::compareByAge));
Run Code Online (Sandbox Code Playgroud)
我只是想知道,如果已经有一些实现的东西,它会在一次运行中完成,例如groupingBySorted.
有没有办法窥视流中的下一个元素?这个想法来自一个对象列表的流,其中应该比较两个跟随的对象(以平滑一些差异,但这在这里不重要).作为一个旧for循环,这看起来像:
List<Car> autobahn = getCars();
for (int i = 0; i < autobahn.size()-1; i++) {
if(autobahn.get(i).speed>autobahn.get(i+1).speed)
autobahn.get(i).honk();
}
Run Code Online (Sandbox Code Playgroud)
到目前为止流的最佳方式是:
autobahn.stream()
.limit(autobahn.size()-1)
.filter(car -> car.speed < autobahn.get(autobahn.indexOf(car)+1).speed)
.forEach(car -> car.honk());
Run Code Online (Sandbox Code Playgroud)
这个解决方案的主要问题是indexOf方法,因为高速公路上可能有两倍于同一辆车.一个更好的解决方案是某种方式来窥视下一个(或前一个)元素(有一个帮助类,这可能是可能的,但看起来很可怕)
BoxedCar boxedCar = new BoxedCar(autobahn.get(0));
autobahn.stream()
.skip(1)
.filter(car -> boxedCar.setContent(car))
.forEach(car -> car.winTheRace());
Run Code Online (Sandbox Code Playgroud)
与助手类
class BoxedCar {
Car content;
BoxedCar(Car content) {
this.content = content;
}
boolean setContent(Car content) {
double speed = this.content.speed;
this.content = content;
return content.speed > speed;
}
}
Run Code Online (Sandbox Code Playgroud)
或者转移Stream<Car>到 …
我想在JSP页面中重置会话而不使其失效.原因是,用户可能已经使用会话打开了一个页面并使其无效会抛出一个NullPointerException.由于已经捕获了一个新的会话,我不想添加额外的短语.目标是清除所有属性.
我正在寻找类似的东西:
session = new HttpSession(); //this does obviously not work
Run Code Online (Sandbox Code Playgroud)
另一种选择是(?)
while(session.getAttributeNames().hasMoreElements()){
session.removeAttribute(session.getAttributeNames().nextElement());
} //cleans session?
Run Code Online (Sandbox Code Playgroud)
但我不确定,如果这会删除一些必要的会话属性,如login-data.
有一个很好的方法来做到这一点?
编辑:最好的解决方案是,每次打开某个页面时,都会为该窗口/选项卡创建一个新会话,直到您关闭该选项卡或重新访问该选项卡中的该页面.这个问题是通过尝试解决这个问题而发生的.
我有一个对象列表,并希望检索所有对象的最小值和最大值,并重置此值.我的解决方案是在Object类中有一个方法,它返回值并重置它和Min-Max收集器.因此我的问题是:collect/ 每个实例都map调用每个方法(在这种情况下是getAndResetValue()方法),或者下面的内容是否会被破坏?
MinMax minMax = objects.stream()
.mapToInt(e -> e.getAndResetValue())
.collect(() -> new minMax(startValues), MinMax::addValue, MinMax::compareMinMax);
Run Code Online (Sandbox Code Playgroud)
我的有根据的猜测是,这是真的,因为不需要多次调用这些方法,并且必须映射每个Object.但是,由于我没有找到关于此事的确认(甚至在文档中也没有),这个问题.