Java中是否有任何库可以将字符串“Y”转换为true或将“N”转换为false?
我做了一个枚举,但我不知道这是否是最好的方法:
public enum BooleanEnum {
TRUE("Y"), FALSE("F");
private String booleanValue;
private BooleanEnum(String booleanValue) {
this.booleanValue = booleanValue;
}
public String getBooleanValue() {
return booleanValue;
}
}
Run Code Online (Sandbox Code Playgroud)
并使用:
if (BooleanEnum.TRUE.getBooleanValue().equals(cpoPipelineDTO.getCpoPipelineCategory().getIsDataFlow())) {
Run Code Online (Sandbox Code Playgroud) 首先我创建了一个空文件,然后我调用了一些线程来搜索数据库并获取结果内容,然后附加到文件中。结果内容为Stringtype,可能为20M。每个线程应该一次写入一个文件。我测试了很多次,我发现没有必要锁定。那正确吗?例子总共1000行,什么时候需要加写锁对文件进行操作?
String currentName = "test.txt";
final String LINE_SEPARATOR = System.getProperty("line.separator");
ThreadPoolExecutor pool = new ThreadPoolExecutor(
10, 100, 10, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
for (int i = 0; i < 500; i++) {
pool.execute(() -> {
try {
appendFileByFilesWrite(currentName, "abc" +
ThreadLocalRandom.current().nextInt(1000) + LINE_SEPARATOR);
} catch (IOException e) {
e.printStackTrace();
}
});
}
IntStream.range(0, 500).<Runnable>mapToObj(a -> () -> {
try {
appendFileByFilesWrite( currentName,
"def" + ThreadLocalRandom.current().nextInt(1000) +
LINE_SEPARATOR);
} catch (IOException e) {
e.printStackTrace();
}
}).forEach(pool::execute);
pool.shutdown();
Run Code Online (Sandbox Code Playgroud)
这是方法:
public static …Run Code Online (Sandbox Code Playgroud) java multithreading java.util.concurrent java-8 threadpoolexecutor
我有一个 Java interface PlatformConfigurable。我也有两个类PlatformProducerConfig和PlatformConsumerConfig.
稍后,我需要向两者添加一个通用配置,将属性设置为空字符串:
private PlatformConfigurable disableHostNameVerificationConfig(PlatformConfigurable platformConfig) {
if (platformConfig instanceof PlatformProducerConfig) {
PlatformProducerConfig oldConfig = (PlatformProducerConfig) platformConfig;
Map<String, String> additionalConfig = oldConfig.additionalProperties();
Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
return oldConfig.toBuilder().additionalProperties(newConfig).build();
}
else if (platformConfig instanceof PlatformConsumerConfig) {
PlatformConsumerConfig oldConfig = (PlatformConsumerConfig) platformConfig;
Map<String, String> additionalConfig = platformConfig.additionalProperties();
Map<String, String> newConfig = new HashMap<>(Optional.ofNullable(additionalConfig).orElseGet(ImmutableMap::of));
newConfig.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "");
return oldConfig.toBuilder().additionalProperties(newConfig).build();
}
return platformConfig;
}
Run Code Online (Sandbox Code Playgroud)
我正在转换为生产者或消费者配置,因为PlatformConfigurable接口没有在其中声明.toBuilder()或.build()方法,并且我无权修改接口,因为我只能实现它。
我想摆脱重复的代码:
Map<String, …Run Code Online (Sandbox Code Playgroud) 我试图获取一个元素列表,对这些元素的一部分进行一些操作,并将这些操作的输出放在一个新列表中。我只想在列表中进行一次迭代。
我发现这样做的唯一方法是:
List<Integer> newList = numList.stream().reduce(new ArrayList<Integer>(),
(acc, value) -> {
if (value % 2 == 0) {
acc.add(value * 10);
}
return acc;
},
(l1, l2) -> {
l1.addAll(l2);
return l1;
}
);
Run Code Online (Sandbox Code Playgroud)
如您所见,这非常麻烦。
我当然可以使用filterand then map,但在这种情况下,我将列表迭代两次。
在其他语言(例如Javascript)中,这种reduce操作非常简单,例如:
arr.reduce((acc, value) => {
if (value % 2 == 0) {
acc.push(value * 10);
}
return acc;
}, new Array())
Run Code Online (Sandbox Code Playgroud)
惊人的!我在想 Java 是否有更好的版本来减少这种减少,或者我编写的 Java 代码是执行此类操作的最短方法。
考虑以下示例:
public static void main(String[] args) {
Function<String, Integer> f1 = str -> str.length();
f1.andThen(i -> {
System.out.println("length is " + i);
return "why do I need to return a String here?";
}).apply("12345");
}
Run Code Online (Sandbox Code Playgroud)
我试图理解为什么我必须返回String。
这背后的逻辑是什么?我希望这andThen会接受Consumer<Integer>让我们说或类似的东西。
那么为什么andThen()要求我返回原始输入的类型呢?
更新:Integer[][]用作 src 数组类型可以使以下代码工作。
我想转换int[][]为List<List<Integer>>并尝试使用:
int[][] arr = new int[][]{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}};
List<List<Integer>> ll = Arrays.stream(arr)
.map(Arrays::asList) // I expect this produces Stream<List<Integer>> but it was actually a Stream<List<int[]>>.
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
编译器发出错误:
| Error:
| incompatible types: inference variable T has incompatible bounds
| equality constraints: java.util.List<java.lang.Integer>
| lower bounds: java.util.List<int[]>
| List<List<Integer>> ll = Arrays.stream(arr).map(Arrays::asList).collect(Collectors.toList());
| ^-----------------------------------------------------------------^
Run Code Online (Sandbox Code Playgroud) 迭代 aMap<Integer, List<String>>并转换为 type List<KeyPair>。在 java 8 (Using streams) 中任何更好的方法来做到这一点。
幼稚的方式:
final List<KeyPair> keyPairs = Lists.newArrayList();
for (final Map.Entry<Integer, List<String>> entry : map.entrySet()) {
for (final String value : entry.getValue()) {
keyPairs.add(new KeyPair()
.withHashKey(value)
.withRangeKey(entry.getKey()));
}
}
Run Code Online (Sandbox Code Playgroud) 我需要查找给定列表中是否有 18 岁以上的用户。如果没有超过 18 岁的用户,则该方法应返回 -1。否则,它应该返回最年轻用户的年龄。
在使用流时,我创建了以下方法,但是,流被使用了两次。有没有更好的方法来使用流来做到这一点
public int test(List<User> userList) {
List<User> usersOver18 = userList.stream()
.filter(emp -> emp.getAge() > 18)
.collect(Collectors.toList());
if (usersOver18.isEmpty()) {
return -1;
}
return usersOver18.stream()
.min(Comparator.comparing(User::getAge))
.get().getAge();
}
Run Code Online (Sandbox Code Playgroud) 我必须设置一个标志nameRemoved=true,当我从List<String>
这是我在这里使用的传统方法。
List<String> list = new ArrayList<String>();
if (list.contains("abc")) {
list.remove("abc");
nameRemoved=true
}
Run Code Online (Sandbox Code Playgroud)
我可以使用下面的方法从列表中删除元素,但如何将标志值设置为nameRemoved=true使用 lambda 语法?
List<String> list = new ArrayList<String>();
list.removeIf(name -> name.equalsIgnoreCase("abc"));
Run Code Online (Sandbox Code Playgroud) 我有文件 abbreviations.txt,其中包含特殊信息:
示例 abbreviations.txt :
PCAP_Personal Computer_Apple
NBHP_NoteBook_Hewlett Packard
TVSG_Televisor_Samsung
Run Code Online (Sandbox Code Playgroud)
我需要将所有品牌名称放入新的列表字符串中。我正在尝试使用这个:
Stream<String> abbreviations = Files.lines(Paths.get("src/main/resources/raceData/abbreviations.txt"))
.flatMap(Pattern.compile("_")::splitAsStream);
List<String> dates = abbreviations.collect(Collectors.toList());
dates.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
但作为 List 我得到:
PCAP_Personal Computer
Apple
TVSG_Televisor
Samsung
NBHP_NoteBook
Hewlett Packard
Run Code Online (Sandbox Code Playgroud) java ×10
java-8 ×10
java-stream ×3
lambda ×3
arrays ×1
collections ×1
generics ×1
hashmap ×1
reducing ×1