假设我有一个具有这种签名的函数:
public static <T> List<Future<T>> invokeAll(Stream<Callable<T>> tasks) {
... submit given tasks using executor ...
}
Run Code Online (Sandbox Code Playgroud)
我有一个数据流,应该"包装"成可调用的并传递给这个函数.如下的天真映射不起作用:
Stream<String> ids = Stream.of("1", "2", "3");
invokeAll(ids.map((id) -> {
// Do a long computation with given ID...
return Boolean.TRUE; // Compilation error: Type mismatch: cannot convert from Boolean to Callable<Object>
}));
Run Code Online (Sandbox Code Playgroud)
一种解决方案是返回返回lambda的lambda:
invokeAll(ids.map((id) -> {
return () -> {
// Do a long computation with given ID...
return Boolean.TRUE;
};
}));
Run Code Online (Sandbox Code Playgroud)
另一个(在某种程度上等效)是使用辅助函数:
public static <T> Callable<T> createCallable(T id) {
return () -> { …Run Code Online (Sandbox Code Playgroud) 我在下面的代码中有一个嵌套循环,我正在尝试优化,因为我知道嵌套for循环是非常昂贵的,任何人都有不同的方法来实现这一点?
提前致谢!
private List<Map<String, Object>> updateSomething(List<Map<String, Object>> list)
throws MetadataException {
for (Map<String, Object> map : list) {
setFilePathAndOffsetParams(map);
for (Map.Entry<String, String> entry : anotherMap.entrySet()) {
updateKeyOnMap(map, entry.getKey(), entry.getValue());
}
}
return list;
}
private void updateKeyOnMap(Map<String, Object> map, String newKey, String oldKey) {
if (!newKey.equals(oldKey)) {
map.put(newKey, map.get(oldKey));
map.remove(oldKey);
}
Run Code Online (Sandbox Code Playgroud) 比方说我有一个List<List<Animal>> animals.此嵌套列表表示每个地方包含动物列表的地点列表.
我需要找出至少出现在两个不同地方的动物类型列表.我知道我可以做正常的循环并做到这一点.有什么办法可以通过Stream API完成吗?
例:
List<List<Animal>> animals = new ArrayList<>();
animals.add(Arrays.asList(new Dog(), new Cat()));
animals.add(Arrays.asList(new Dog(), new Bird()));
animals.add(Arrays.asList(new Bird()));
Run Code Online (Sandbox Code Playgroud)
预期(相当于):
List<Class<? extends Animal>> animalTypes = Arrays.asList(Dog.class, Bird.class);
Run Code Online (Sandbox Code Playgroud)
至于尝试,我只设法将内部列表转换为一组类:
animals.stream().map(place -> place.stream().map(animal -> animal.getClass()).collect(Collectors.toSet()));
Run Code Online (Sandbox Code Playgroud)
没有Stream API的代码:
final List<List<Animal>> animals = new ArrayList<>();
animals.add(Arrays.asList(new Dog(), new Cat()));
animals.add(Arrays.asList(new Dog(), new Bird()));
animals.add(Arrays.asList(new Bird()));
final Map<Class<? extends Animal>, Integer> count = new HashMap<>();
for (final List<Animal> place : animals) {
final Set<Class<? extends Animal>> uniqueTypes = new HashSet<>();
for …Run Code Online (Sandbox Code Playgroud) 使用Java 8流API,我想要一种方法来调用一个接受两个参数的引用方法.splitFileByMaxRows是一个应该采用a String和a int作为参数的引用方法.有没有办法实现它?
private void breakLargeFileIntoChunks(final File setlFile, int parentFileId) {
LOG.info(LOG.isInfoEnabled() ? "*** Breaking Large File Into Chunks ***" : null);
try (Chunker chunker = new Chunker();
Stream<String> lines = Files.lines(Paths.get(setlFile.getAbsolutePath()))) {
lines.forEach(chunker::splitFileByMaxRows);
}
catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud) 我们有一种方法,其中我们接收一个Optional<SomeType>对象.如果包含的SomeType对象不为null,那么我们必须SomeOtherType使用对象的字段初始化SomeType对象并返回该新对象; 否则我们必须返回null
我们找到了多个不同的解决方案,我们用两个语句执行此任务,首先检索可选对象,然后再创建另一个类型对象,例如
private SomeOtherType ourMethod() {
SomeType someObject = getOptionalSomeTypeFromSomeWhere().orElse(null);
return someObject != null ? new SomeOtherType(someObject.getField1(), someObject.getField2(), ...) : null;
}
Run Code Online (Sandbox Code Playgroud)
有可能用一个陈述来涵盖这个吗?到目前为止,我们无法进行空检查,访问字段,创建新对象等
基本上这个问题的一个更复杂的情况:获取可选对象的字段或返回null
Set<String> unique = new HashSet<>();
List<String> duplicates = new ArrayList<>();
for (Animal cat: animals) {
if (!unique.add(cat.getName())) {
duplicates.add(cat.getName());
}
}
return duplicates;
Run Code Online (Sandbox Code Playgroud)
我想知道是否有办法简化这个?我是Java流的新手,我尝试使用Map,但我采用了传统的for循环.
firstlist
.stream()
.map( x -> {
return secondList
.stream()
.map( y -> { //return a string } )
.collect(Collectors.toList()) // "Output" I need
}
)
.//Get the "Output" here
Run Code Online (Sandbox Code Playgroud)
我有两个清单。第一个列表中的项目必须与第二个列表进行比较,并且必须建立新的列表。
样本输入
List 1 : [ { "id" ; 3, "names" : ["test","test2"] }]
List 2 : [ {"name": :"test" , "age" :3}]
Run Code Online (Sandbox Code Playgroud)
输出:
List 3 : [ {"id" : 3, "name" : "test", "age" :3} ]
Run Code Online (Sandbox Code Playgroud)
PS:names应该对照第二个清单检查第一个清单中的清单
我有一个对象列表,我想使用两个属性对其进行排序.我在互联网上搜索过,我在java 8中找到了这个解决方案.
class ClassA {
String var2;
String var1;
// getters and setters
}
List<classA> list;
list.sort(Comparator.comparing(ClassA::getVar1).thenComparing(ClassA::getVar2));
Run Code Online (Sandbox Code Playgroud)
这绝对有效,但我想要的是在var2上使用降序排序,在var1上使用升序排序.
我有一张Map<String, List<String>>地图,我希望从中提取一个List<String>包含地图中所有字符串列表的字符串.我想使用java8流语法.
在旧的Java我会做:
List<String> all = new LinkedList<String>();
for (String key: map.keySet()) {
all.addAll(map.get(key));
}
return all;
Run Code Online (Sandbox Code Playgroud)
如何使用流?
给出从名称到数字列表的映射.
我想使用java 8 stream api计算每个Name的平均值.
Map<String, List<Double>> NameToQuaters = new HashMap<>();
Map<String, Double> NameToMean = ?
Run Code Online (Sandbox Code Playgroud)