我想找出一个字符串流是否至少有一个出现在另一个字符串String中Set<String>.我想出了两个解决方案.
性能方面,哪种方法最好/推荐?
1)
return source.stream().filter(this::streamFilter).count() > 0;
Run Code Online (Sandbox Code Playgroud)
2)
return source.stream().anyMatch(this::streamFilter);
Run Code Online (Sandbox Code Playgroud)
这是streamFilter方法:
private boolean streamFilter(String str) {
return filterKeywords.contains(str.toLowerCase());
}
Run Code Online (Sandbox Code Playgroud)
filterKeywords: private Set<String> filterKeywords;
或者有更好的方法吗?
我有一个方法params是一个大于50000项的列表; 限于业务逻辑,列表必须小于30000,所以我有一个方法在逻辑之前将这个数组拆分为2d数组
public static final <T> Collection<List<T>> partitionBasedOnSize(List<T> inputList, int size) {
AtomicInteger counter = new AtomicInteger(0);
return inputList.stream().collect(Collectors.groupingBy(s -> counter.getAndIncrement() / size)).values();
}
Run Code Online (Sandbox Code Playgroud)
这是我目前的解决方案:
public List<Account> getChildrenList(List<Long> ids) {
List<Account> childrenList = new ArrayList<>();
Collection<List<Long>> childrenId2dList = PartitionArray.partitionBasedOnSize(childrenIdsList, 30000);
for (List<Long> list : childrenId2dList) {
//this is my business logic: start
childrenList.addAll(accountRepository.getAccounts(list));
//this is my business logic: end
}
return childrenAccountsList;
}
Run Code Online (Sandbox Code Playgroud)
我想在方法的顶部创建一个注释,而不是许多重复的代码(每次检查和讨厌......)
当我的 Java 程序与 Java 8 和 Java 11 一起运行时,我有一个非常奇怪的行为差异。
我正在使用 MSGraph API (1.7.0) 对 Onedrive API 进行多次调用。为了进行这些调用,我使用了 4 个并行线程来同步硬盘上的大量文件(大约 1000 个)。
当我使用 Java 8 执行程序时,我没有发现任何异常。当我使用 java 11 执行它时,我在大约 60% 的调用中收到了 Socket Timeout Exception。
要配置IGraphServiceClient,我使用的是默认配置。就我而言,在这种情况下,HTTP 提供程序是 OKHttp3。
有没有人经历过这样的事情?
[更新-1]
这些是我测试过的环境:
在此您有堆栈跟踪:
com.microsoft.graph.core.ClientException: Error during http request
at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal(CoreHttpProvider.java:422) ~[easybox-0.1-SNAPSHOT.jar:?]
at com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:204) ~[easybox-0.1-SNAPSHOT.jar:?]
at com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:184) ~[easybox-0.1-SNAPSHOT.jar:?]
at com.microsoft.graph.http.BaseStreamRequest.send(BaseStreamRequest.java:85) ~[easybox-0.1-SNAPSHOT.jar:?]
at com.microsoft.graph.requests.extensions.DriveItemStreamRequest.get(DriveItemStreamRequest.java:55) …Run Code Online (Sandbox Code Playgroud) 我很确定bootstrap.servers是正确的.Maven中有什么冲突或Kafka有什么问题吗?
在此之前它成功地运作了.我添加了一些Maven或Spark然后出了点问题..
谁能知道如何解决它?
这是java中的kafka代码
Properties props = new Properties();
props.put("bootstrap.servers", "x.xx.xxx.xxx:9092");
props.put("metadata.broker.list", "x.xx.xxx.xxx:9091, x.xx.xxx.xxx:9092, x.xx.xxx.xxx:9093");
props.put("producer.type", "async");
props.put("batch.size", "500");
props.put("compression.codec", "1");
props.put("compression.topic", topicName);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
org.apache.kafka.clients.producer.Producer<String, String> producer = new KafkaProducer<String, String>(
props);
Run Code Online (Sandbox Code Playgroud)
获取错误在引导服务器中没有给出可解析的引导程序URL,
[err] at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:335)
[err] at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:188)
[err] at com.wra.controller.ParserController.GetResumeUpload(ParserController.java:98)
[err] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[err] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
[err] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
[err] at java.lang.reflect.Method.invoke(Method.java:508)
[err] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
[err] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
[err] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
[err] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
[err] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
[err] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
[err] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
[err] …Run Code Online (Sandbox Code Playgroud) 我有这个代码:
public enum Continent {ASIA, EUROPE}
public class Country {
private String name;
private Continent region;
public Country (String na, Continent reg) {
this.name = na;
this.region = reg;
}
public String getName () {return name;}
public Continent getRegion () {return region;}
@Override
public String toString() {
return "Country [name=" + name + ", region=" + region + "]";
}
}
Run Code Online (Sandbox Code Playgroud)
在主要班级:
public static void main(String[] args) throws IOException {
List<Country> couList = Arrays.asList(
new Country ("Japan", Continent.ASIA),
new Country …Run Code Online (Sandbox Code Playgroud) 我可以使用方法参考转换以下代码吗?
List<Text> childrenToRemove = new ArrayList<>();
group.getChildren().stream()
.filter(c -> c instanceof Text)
.forEach(c -> childrenToRemove.add((Text)c));
Run Code Online (Sandbox Code Playgroud)
让我举一个例子来说明我的意思,假设我们有
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(elem -> System.out.println(elem));
Run Code Online (Sandbox Code Playgroud)
使用方法引用它可以写成(最后一行)
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
将表达式转换为方法引用的规则是什么?
我无法确定为什么在流上操作findAny()后抛出空指针异常filter().在这个特定的测试用例中,过滤器操作应该已经过滤掉所有内容,但没有结果findAny().
Optional<JsonNode> encryption = sseEncryptionList.stream()
.filter(n -> n.textValue().equals("AES256")) //Filters out everything
.findAny(); //Throws null pointer exception
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at example.Main.lambda$main$0(Main.java:41)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1351)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findAny(ReferencePipeline.java:469)
at example.Main.main(Main.java:42)
Run Code Online (Sandbox Code Playgroud)
findAny()如果流不包含任何元素,这是否会抛出空指针异常?
编辑:解决可能过滤掉所有元素的过滤操作的优雅和功能方法是什么?
所以我有一个列表,我从中获得一个并行流来填写地图,如下所示:
Map<Integer, TreeNode> map = new HashMap<>();
List<NodeData> list = some_filled_list;
//Putting data from the list into the map
list.parallelStream().forEach(d -> {
TreeNode node = new TreeNode(d);
map.put(node.getId(), node);
});
//print out map
map.entrySet().stream().forEach(entry -> {
System.out.println("Processing node with ID = " + entry.getValue().getId());
});
Run Code Online (Sandbox Code Playgroud)
这段代码的问题在于,当"放置数据"过程仍在进行时(因为它是并行的),地图正在被打印出来,因此,地图尚未从列表中接收到所有元素.当然,在我的真实代码中,不仅仅是打印出地图; 我使用地图来利用O(1)查找时间.
我的问题是:
如何使主线程等待,以便在打印出地图之前完成"放置数据"?我试图把"把数据"线程T内,做t.start()和t.join(),但是这并没有帮助.
也许在这种情况下我不应该使用并行流?列表很长,我只想利用并行性来提高效率.
java collections parallel-processing multithreading java-stream
我有以下示例数据集,我想根据方向的值使用Java流api进行转换/缩减
Direction int[]
IN 1, 2
OUT 3, 4
OUT 5, 6, 7
IN 8
IN 9
IN 10, 11
OUT 12, 13
IN 14
Run Code Online (Sandbox Code Playgroud)
至
Direction int[]
IN 1, 2,
OUT 3, 4, 5, 6, 7
IN 8, 9, 10, 11
OUT 12, 13
IN 14
Run Code Online (Sandbox Code Playgroud)
到目前为止我写的代码
enum Direction { IN, OUT }
class Tuple {
Direction direction;
int[] data;
public Tuple merge(Tuple t) {
return new Tuple(direction, concat(getData(), t.getData()));
}
}
private static int[] concat(int[] first, int[] second) …Run Code Online (Sandbox Code Playgroud) 我正在尝试重构一些代码以返回可选列表而不是可选。
我的班级有以下清单
private final List<Mapper<? extends Message>> mappers;
Run Code Online (Sandbox Code Playgroud)
有一个私有方法可以为这些映射器创建特征并返回消息列表
private List<Message> mapToFeature() {
mappers.stream()
.map(mapper -> mapper.createFeature())
.collect(Optionals.toList());
}
Run Code Online (Sandbox Code Playgroud)
Mapper 的界面如下所示:
public interface Mapper<T extends Message> {
Optional<T> createFeature();
}
Run Code Online (Sandbox Code Playgroud)
该Optionals.toList()方法返回一个收集器以将当前选项过滤到列表中。
我想更改接口(以及所有相应的类)以返回可选列表
public interface Mapper<T extends Message> {
List<Optional<T>> createFeature();
}
Run Code Online (Sandbox Code Playgroud)
我在Options util 中没有方法从多个列表中过滤当前选项。我如何能够在不对 util 类进行任何更改的情况下执行相同的操作?
java ×10
java-8 ×8
java-stream ×7
apache-kafka ×1
collections ×1
collectors ×1
java-11 ×1
lambda ×1
maven ×1
okhttp ×1
reduce ×1