对于学校作业,我必须实现一种方法,该方法将返回字符串中最长的重复子字符串。但我必须仅使用 Stream API 来完成此操作。
这是我到目前为止所做的:
public static String biggestRedundantSubstring(String s) {
Stream.Builder<String> stringBuilder = Stream.builder();
while (!Objects.equals(s, "")) {
stringBuilder.add(s);
s = s.substring(1);
}
return stringBuilder.build().sorted().reduce("",
(String biggestRedundantSubstring, String matchingPrefix) ->
biggestRedundantSubstring.length() > matchingPrefix.length() ?
biggestRedundantSubstring : matchingPrefix,
(String sub1, String sub2) -> {
String matchingPrefix = "";
int limitIndex = Math.max(sub1.length(), sub2.length()) - 1;
for (int i = 0; i < limitIndex; i++) {
if (sub1.charAt(i) == sub2.charAt(i)) {
matchingPrefix += sub1.charAt(i);
} else {
break;
}
}
return …Run Code Online (Sandbox Code Playgroud) 如何获取实际流以便从Optional 中过滤或映射方法?例如
Optional.ofNullable(id)
.map(this:loadAllById) // method loadAllById return a stream (now is wrapped in Optional<Stream>)
.filter(obj -> obj.status) // here i have no access to object in stream but to the full stream
Run Code Online (Sandbox Code Playgroud)
由此也产生了一个疑问。在Optional中包含一个流是否正确?由于流应该始终不为空(如果为空),是否不需要检查?
我想收集 a 内调用的方法返回的值forEach:
@PostMapping(value="insert-ppl")
public String insertPeople(@RequestBody @Valid @NotNull List<Person> people){
people.forEach(this::insertPerson);
}
Run Code Online (Sandbox Code Playgroud)
该insertPerson方法返回一个字符串,表明数据库中的插入是否成功。我想获取每次调用返回的字符串insertPerson。但我不能使用,.collect因为它不是流。
我怎样才能做到这一点?
我遇到一个特定的用例,如果对象为空,我经常需要将它们包装起来Optional。看一下这段代码:
List<AbstractCorporateAction> cas = stream.toList();
if (cas.isEmpty()) return Optional.empty();
else return Optional.of(cas);
Run Code Online (Sandbox Code Playgroud)
我检查列表是否为空,如果确实为空,则返回一个空可选,如果不是,则将其包装。原因是有时我得到列表本身的空值,有时我得到一个实际的列表,但它是空的。
通过这种方法,当返回的可选本身为空时,我不需要仔细检查底层列表。
但对于不同的数据结构,实现方式有所不同。是否有第三方库的内置方法可以实现此目的?我得到的最接近的是 fromGuava.MoreObjects#isEmpty但它只检查对象是否为空,并且在它为空的情况下不返回可选值。
我可以为此编写自己的封面,但我正在寻找一种专业、可靠的方法来实现所需的功能。
请建议将路线转换为routeMap的更好方法。
lateinit var routes: List<Pair<String, String>>
val routesMap = HashMap<String, ArrayList<String>>
routes.forEach {
routesMap.getOrPut(it.first) { ArrayList<String>() }.add(it.second)
}
Run Code Online (Sandbox Code Playgroud) 我有下面的清单。
List<String> firstName = List.of("Monika","Shweta", "Shruti","Anuradha");
List<String> lastName = List.of("Mishra","Hariharno","Sharma","Mishra");
List<Integer> sal = List.of(5000000,50,500,100000);
List<List<?>> finalList = List.of(firstName,lastName,sal);
finalList.stream().flatMap(s->s.stream()).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
当我使用它打印时,flatMap()它会打印所有firstname, lastname, 然后sal.
我想firstName : lastName:sal按顺序将所有这些打印在一起。例如
Monika:Mishra:5000000
Run Code Online (Sandbox Code Playgroud)
是否可以使用flatMap或任何其他java8功能?
我想知道检查列表是否为空的最佳方法是什么。在我的直播中,我拨打了orElseThrow两次电话。它有效,但我不知道它是否正确?看起来有点难看:
Optional.ofNullable(listCanBeNull)
.orElseThrow(() -> new ResourceNotFoundException("the same error message"))
.stream()
.filter(configuration -> configuration.getId().equals(warehouseConfigurationId))
.findAny()
.orElseThrow(() -> new ResourceNotFoundException("the same error message"));
Run Code Online (Sandbox Code Playgroud)
当列表为空且未找到任何项目时,我必须抛出错误
我的代码:
final List<Employee> empList= getEmployeeList();
String empid = "1234";
Employee selectedEmp = new Employee();
for (Employee e1: empList) {
if (empid .equals(e1.getEmpid()))
selectedEmp = e1;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想用Java 8重写上面的代码。
我尝试过以下方法,但没有成功。我无法弄清楚翻译-if语句:
empList.stream()
.foreach( <how to apply if condition here>)
Run Code Online (Sandbox Code Playgroud) 我最近进入了最后一轮面试。
在面试中,他们有一次要求我通过以下代码展示我的 Java 8 知识。Optional.of()他们要求我使用或 来减少以下代码Stream.of()。我完全被冻结了,我只使用过列表上的流,不知道如何使用可选方法。我没有专门因为这个原因得到这份工作,因为他们说我对java8的理解还不够好。有人可以告诉我他们在找什么吗?
概括
我被特别要求用or减少这些2行:Optional.of()Stream.of()
gameDto = gameplay.playRandomGame(gameDto);
repo.updateTotals(gameDto.getResult());
Run Code Online (Sandbox Code Playgroud)
一些上下文的总体片段:
@Service("gameService")
public class GameServiceImpl implements GameService{
@Autowired
private SessionInMemoryRegistry sessionRegistry;
@Autowired
private GameInMemoryRepo repo;
@Autowired
private GamePlay gameplay;
@Override
public ResponseDto addGameToSession(GameDto gameDto) {
gameDto = gameplay.playRandomGame(gameDto);
repo.updateTotals(gameDto.getResult());
return sessionRegistry.addGameSession(gameDto.getSessionId(), gameDto.getPlayer1Choice(), gameDto.getPlayer2Choice(), gameDto.getResult());
}
}
Run Code Online (Sandbox Code Playgroud) 我想从 Java 8+ 中的 Map<String,Integer> 收集最大数字列表的关联键
例如:
final Map<String, Integer> map = new HashMap<>();
map.put("first", 50);
map.put("second", 10);
map.put("third", 50);
Run Code Online (Sandbox Code Playgroud)
在这里我想返回与最大值关联的键列表。
对于上面的例子,预期输出是[first,third]。因为这两个键具有相同的最大值。
我尝试使用以下方法,但只能获得单个最大密钥。
final String maxKey = map.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
final List<String> keysInDescending = map.entrySet()
.stream()
.sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(maxKey); // third
System.out.println(keysInDescending); //[third, first, second]
Run Code Online (Sandbox Code Playgroud)
但我的预期输出是[第一,第三]。在Java 8+版本中如何实现呢?
java-stream ×10
java ×9
option-type ×3
collections ×2
flatmap ×2
java-8 ×2
algorithm ×1
android ×1
guava ×1
if-statement ×1
java-17 ×1
kotlin ×1
lambda ×1
list ×1
string ×1
substring ×1