我尝试使用parallelStream()带有Spring @Transactional注释的DAO 并得到这样的问题:
@Transactional
public void processCollection(Collection<Object> objects) {
objects.parallelStream()
.forEach(this::processOne); //throw exception
}
@Transactional
public void processOne(Object o) {
...
}
Run Code Online (Sandbox Code Playgroud)
工作正确:
@Transactional
public void processCollection(Collection<Object> objects) {
objects.stream()
.forEach(this::processOne); //work correctly
}
@Transactional
public void processOne(Object o) {
...
}
Run Code Online (Sandbox Code Playgroud)
例外:
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
Run Code Online (Sandbox Code Playgroud)
我如何使用带@Transactional注释的方法parallelStream()?
更新 为什么会发生这种情况Spring事务管理器和多线程 但是我希望Spring 4支持java 8可以为此提供一些解决方案.有任何想法吗?
我有一个包含URL和电子邮件的文本文件.我需要从文件中提取所有这些内容.每个URL和电子邮件可以找到一次以上,但结果不应包含重复项.我可以使用以下代码提取所有URL:
Files.lines(filePath).
.map(urlPattern::matcher)
.filter(Matcher::find)
.map(Matcher::group)
.distinct();
Run Code Online (Sandbox Code Playgroud)
我可以使用以下代码提取所有电子邮件:
Files.lines(filePath).
.map(emailPattern::matcher)
.filter(Matcher::find)
.map(Matcher::group)
.distinct();
Run Code Online (Sandbox Code Playgroud)
我是否可以提取所有Files.lines(filePath)只读取一次返回的流的URL和电子邮件?类似于将行流分割为URL流和电子邮件流的东西.
我正在使用.txt文件读取数字BufferedReader.我想颠倒这种蒸汽中元素的顺序,这样当它们被收集时,它们将从最高到最低排列.我不想在构建数组后进行排序,因为我不知道它中可能有多少个元素,我只需要最高的N个元素.
in = new BufferedReader(reader);
int[] arr = in.lines()
.mapToInt(Integer::parseInt)
.sorted()
.limit((long) N)
.toArray();
Run Code Online (Sandbox Code Playgroud) 我正在寻找最优雅的方式来创建DoubleStream(使用总和,平均等)List<Double>.目前我有这样的代码:
List<Double> doubles = getListOfDoubles();
double sum = doubles.stream()
.mapToDouble(d -> d)
.sum();
Run Code Online (Sandbox Code Playgroud)
也许有人可以建议更短的方式?
我继续学习java 8.
我发现了有趣的行为:
让我们看看代码示例:
// identity value and accumulator and combiner
Integer summaryAge = Person.getPersons().stream()
//.parallel() //will return surprising result
.reduce(1, (intermediateResult, p) -> intermediateResult + p.age,
(ir1, ir2) -> ir1 + ir2);
System.out.println(summaryAge);
Run Code Online (Sandbox Code Playgroud)
和模型类:
public class Person {
String name;
Integer age;
///...
public static Collection<Person> getPersons() {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Vasya", 12));
persons.add(new Person("Petya", 32));
persons.add(new Person("Serj", 10));
persons.add(new Person("Onotole", 18));
return persons;
}
}
Run Code Online (Sandbox Code Playgroud)
12 + 32 + 10 + 18 = 72
对于序列流,此代码始终返回73(72 …
我有一个像这样的列表:
List<Map<String, Long>>
Run Code Online (Sandbox Code Playgroud)
有没有办法,使用lambda,将此列表转换为:
Map<String, List<Long>>
Run Code Online (Sandbox Code Playgroud)
例:
Map<String, Long> m1 = new HashMap<>();
m1.put("A", 1);
m1.put("B", 100);
Map<String, Long> m2 = new HashMap<>();
m2.put("A", 10);
m2.put("B", 20);
m2.put("C", 100);
List<Map<String, Long>> beforeFormatting = new ArrayList<>();
beforeFormatting.add(m1);
beforeFormatting.add(m2);
Run Code Online (Sandbox Code Playgroud)
格式化后:
Map<String, List<Long>> afterFormatting;
Run Code Online (Sandbox Code Playgroud)
看起来像是这样的:
A -> [1, 10]
B -> [100, 20]
C -> [100]
Run Code Online (Sandbox Code Playgroud) 我有一个重要的数据集,并希望调用缓慢但干净的方法,而不是调用快速方法,副作用对第一个结果.我对中间结果不感兴趣,所以我不想收集它们.
显而易见的解决方案是创建并行流,进行慢速呼叫,再次使流顺序,并进行快速呼叫.问题是,所有代码都在单线程中执行,没有实际的并行性.
示例代码:
@Test
public void testParallelStream() throws ExecutionException, InterruptedException
{
ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);
Set<String> threads = forkJoinPool.submit(()-> new Random().ints(100).boxed()
.parallel()
.map(this::slowOperation)
.sequential()
.map(Function.identity())//some fast operation, but must be in single thread
.collect(Collectors.toSet())
).get();
System.out.println(threads);
Assert.assertEquals(Runtime.getRuntime().availableProcessors() * 2, threads.size());
}
private String slowOperation(int value)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return Thread.currentThread().getName();
}
Run Code Online (Sandbox Code Playgroud)
如果我删除sequential,代码按预期执行,但显然,非并行操作将在多个线程中调用.
你能推荐一些关于这种行为的引用,或者某些方法可以避免临时收集吗?
我有以下代码("代码"是一个数组变量):
Arrays.asList(codes)
.stream()
.filter(code -> code.hasCountries())
.sorted()
.toArray()
);
Run Code Online (Sandbox Code Playgroud)
编译器给我以下错误:
令牌")"上的语法错误,ElidedSemicolonAndRightBrace预期
这有什么不对?
我有一个List<String>只通过使用流API我将所有字符串设置为小写,将它们从最小的字符串排序到最大字符串并打印它们.我遇到的问题是将字符串的第一个字母大写.
这是我做的事.stream().map()吗?
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("SOmE", "StriNgs", "fRom", "mE", "To", "yOU");
list.stream()
.map(n -> n.toLowerCase())
.sorted((a, b) -> a.length() - b.length())
.forEach(n -> System.out.println(n));;
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
me
to
you
some
from
strings
Run Code Online (Sandbox Code Playgroud)
期望的输出:
Me
To
You
Some
From
Strings
Run Code Online (Sandbox Code Playgroud) 为什么还有LongSummaryStatistics实现的IntConsumer时候IntSummaryStatistics实现IntConsumer?
java ×10
java-stream ×10
java-8 ×8
collections ×1
eclipse ×1
forkjoinpool ×1
lambda ×1
mapping ×1
reduce ×1
spring ×1