我有以下地图:
private static Map<String, String[]> createMap(){
Map<String, String[]> map = new HashMap<>();
map.put("A", new String[]{null});
map.put("B", new String[]{"Banana"});
map.put("C", new String[]{""});
map.put("D", new String[]{"Duck"});
return map;
}
Run Code Online (Sandbox Code Playgroud)
我想把这张地图转换成Map<String, String>
所需输出:
关键 :B 价值 : 香蕉
关键 :D 值 : 鸭子
我想使用Java 8 Stream APIsand 来执行此操作,并且我尝试过的解决方案之一是
final Map<String, String[]> collect = createMap().entrySet().stream()
.filter(e -> e.getValue()[0] != null && !"".equals(e.getValue()[0]))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
collect.forEach((key, value) -> System.out.println("Key :" + key + " Value :" + Arrays.toString(value)));
Run Code Online (Sandbox Code Playgroud)
但这给了我Map<String, String[]>,输出是 …
我想过滤列表中具有非空属性的元素并返回该属性:
list.stream.map(a -> StringUtils.trimToEmpty(a.getProp())).filter( p -> StringUtils.isNotEmpty(p)).findAny().orElse("");
Run Code Online (Sandbox Code Playgroud)
上面的代码是否首先映射了所有元素?出于效率原因,我想逐个元素地处理。
Javadoc 指出Stream.flatMap (Function <T, Stream<U>> mapper):
每个映射的流在其内容放入该流后都会关闭。
好的。但是异常处理呢?
考虑以下:
public List<Path> search (List<Path> paths) {
return paths.stream ()
.flatMap (dir -> {
try {
return Files.list (dir);
} catch (IOException e) {
throw new UncheckedIOException (e);
}
})
.filter (this::mightThrowException)
.collect (toList ());
}
Run Code Online (Sandbox Code Playgroud)
如果Files.list (Path)在第一次调用时抛出异常,则它的流永远不会首先打开,因此不需要关闭。如果它在以后的调用中抛出异常,则先前调用生成的流都已按照.flapMap ()其规范完全处理并关闭。
但是如果过滤器抛出异常会发生什么?我们正在处理文件列表流,所以我想我需要在某处关闭某些内容,但我不知道到底是什么。最初的paths.stream ()也许?然后哪个会调用派生流上的 close 方法?
注意:对于任何不熟悉Files.list (Path)静态方法的人来说,它返回一个Stream<Path>需要关闭的值(与大多数流不同)。
我正在使用 java NIO 包的方法读取文件Files.lines(),该方法给出类型的输出Stream<String>。对字符串记录进行一些操作后,我想将其写入文件。我尝试使用将其收集到列表中Collectors.toList(),并且它适用于较小的数据集。当我的文件有近 100 万行(记录)时,就会出现问题,列表无法容纳那么多记录。
// Read the file using Files.lines and collect it into a List
List<String> stringList = Files.lines(Paths.get("<inputFilePath>"))
.map(line -> line.trim().replaceAll("aa","bb"))
.collect(Collectors.toList());
// Writes the list into the output file
Files.write(Paths.get("<outputFilePath>"), stringList);
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种可以读取大文件、操作它(如.map()我的示例中的方法中所做的那样)并将其写入文件而不将其存储到列表(或集合)中的方法。
String s = "apples for you";
StringBuilder returnString = new StringBuilder("");
Arrays.stream(s.split(" "))
.reduce(returnString, (acc, str) -> acc.append(str.charAt(0)));
Run Code Online (Sandbox Code Playgroud)
预期输出每个单词的第一个字母,即afy。
但在acc.append,处出现错误acc被视为 a String。
我必须创建一个方法,需要将文件分成多个字节。
示例 byte[] 到 List<byte[]> 中,假设每个大小为 1 MB (sizeMB=1 * 1024 * 1024)
因此 5.2 MB 文件应该由五个 1MB 和一个 2KB 组成。[2kb、1MB、1MB、1MB、1MB、1MB]。
byte[] mainFile=getFIle();
List<bute[]> listofSplitBytes=getFileChunks(mainFile);
public void list<bute[]> getFileChunks(byte[] mainFile) {
int sizeMB = 1 * 1024 * 1024;
// Split the files logic
}
Run Code Online (Sandbox Code Playgroud)
我试图避免添加if then else来处理。我正在尝试寻找是否有更干净的方法来做到这一点,例如使用流或类似的东西?
我正在寻找一种可读的方式来重用流操作链。
我的想法是,我有一定的操作序列,我想将其应用于其他操作之间的多个流。流之间的其他操作并不相同。
因此,例如,对于每个流,我想更改字符串的大小写,修剪它,使空字符串无效,然后过滤掉空值,最后消除重复项,如下所示:
在这两种情况下,我都会执行以下操作序列:
.map( String::trim ).map( Strings::emptyToNull ).filter( Objects::nonNull ).distinct()
Run Code Online (Sandbox Code Playgroud)
我目前复制该链并将其放在多个流的其他操作之间:
myStream1.doSomeStuff().map( String::trim ).map( Strings::emptyToNull ).filter( Objects::nonNull ).distinct().doOtherStuff();
myStream2.doSomethingElse().map( String::trim ).map( Strings::emptyToNull ).filter( Objects::nonNull ).distinct().doSomethingElseStill();
Run Code Online (Sandbox Code Playgroud)
有没有好的方法可以避免重写那段代码?显然,两个 map() 操作是可能的,但是有没有办法实现这种操作组合呢?
如何将具有相同对象属性的列表中的所有对象分组?无需提及 Object 属性值。
型号类别:
public class Item {
private String id;
private String name;
private String team
}
Run Code Online (Sandbox Code Playgroud)
List<item> items = new ArrayList();
我已经尝试过这个:
items.stream().filter(item -> "Elites".equals(item.team)).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
但这需要将团队名称作为参数传递。
我们如何在不指定团队值的情况下对项目进行分组?
并制作一个以Key作为项目的HashMap 。team和value作为带有 team.name 和 item.id 的键值对列表
像这样:
"item.team":{
"item.id":"item.name",
"item.id":"item.name",
"item.id":"item.name",
.....
}
Run Code Online (Sandbox Code Playgroud) 我有一个Map<String, String>
List<String>我想流式传输I call中的所有值keys。
我怎样才能让它从地图返回值?
地图是这样的:
("Frank", "Car")
("Bob", "Bike")
("Jim", "Truck")
Run Code Online (Sandbox Code Playgroud)
我给它的钥匙列表:
["Frank","Jim"]
Run Code Online (Sandbox Code Playgroud)
预期结果:
["Car","Truck"]
Run Code Online (Sandbox Code Playgroud)
我尝试了这个,但它只打印键而不是值。
keys.stream()
.filter(map::containskey)
.collect(Collectors.toList())
Run Code Online (Sandbox Code Playgroud) 我有一组字符串(它是静态的),我想Map<String, List<String>>从它们创建一个,其中列表被初始化为一个新的 ArrayList。类似于以下内容,但此代码不正确。
static Set<String> MY_TYPES = Set.of("type1", "type2", "type3");
Map<String, List<String> myMap = MY_TYPES.stream().map(t->() t, new ArrayList<>()).collect(Collectors.toMap());
Run Code Online (Sandbox Code Playgroud)
我正在尝试学习如何在我的代码中更好地使用流。我知道我可以在集合上进行迭代。
@shmosel,你是对的。我想要相当于
Map.of("type1", new ArrayList<>(), "type2", new ArrayList<>(), "type3", new ArrayList());
Run Code Online (Sandbox Code Playgroud) java ×10
java-stream ×10
java-8 ×6
collections ×2
hashmap ×2
arraylist ×1
exception ×1
file ×1
linked-list ×1
set ×1
split ×1
stream ×1
string ×1