我想知道在Java中调用值并尝试一些代码.
public class Test {
public static void main(String[] args) {
Test test = new Test();
Integer integer = 4;
System.out.println(integer);
test.change(integer);
System.out.println(integer);
}
public void change(Integer integer) {
integer++;
}
}
Run Code Online (Sandbox Code Playgroud)
因为java是按值调用,所以我的输出类似于:
4
5
Run Code Online (Sandbox Code Playgroud)
但它打印出来了
4
4
Run Code Online (Sandbox Code Playgroud)
然后我了解到Integers是不可变的,所以我的方法"change"创建了值为5的新Integer,而main中的"integer"仍然是4.
然后我写了下面的课:
public class Test {
public static void main(String[] args) {
Test test = new Test();
MyInteger myInteger = new MyInteger();
myInteger.x = 4;
System.out.println(myInteger.x);
test.change(myInteger);
System.out.println(myInteger.x);
}
public void change(MyInteger myInteger) {
myInteger.x++;
}
}
class MyInteger {
Integer x; …Run Code Online (Sandbox Code Playgroud) 我有这样的代码:
Map<String, String> args = new HashMap<>();
args.put("-T", "Tom Sawyer");
// args.put("-I", "1112223334");
if (args.containsKey("-T")) {
Book book = libraryService.findBookByTitle(args.get("-T"));
} else {
Book book = libraryService.findBookByIsbn(args.get("-I"));
}
Run Code Online (Sandbox Code Playgroud)
LibraryService:
public class LibraryService {
private final BookRepository bookRepository = new BookRepository();
public Book findBookByTitle(String title) {
return bookRepository.findByTitle(title);
}
public Book findBookByIsbn(String isbn) {
return bookRepository.findByIsbn(isbn);
}
Run Code Online (Sandbox Code Playgroud)
BookRepository:
public class BookRepository {
private List<Book> books = new ArrayList<>();
public Book findByIsbn(String isbn) {
return books.stream()
.filter(s -> s.getIsbn().equals(isbn))
.findFirst()
.orElseThrow(() -> …Run Code Online (Sandbox Code Playgroud) 我有一个文件,其中一些数据用分号分隔.我正在尝试构建一个流,它将逐行读取文件,将每列数据分开并将其映射到新对象.
data.txt中:
John;Smith;42;shopassistant
Clara;Lefleur;24;programmer
Run Code Online (Sandbox Code Playgroud)
Person.class:
public class Person{
String name;
String lastName;
int age;
String job;
}
Run Code Online (Sandbox Code Playgroud)
我从这样的事情开始:
List<Person> people = Files.lines(Paths.get("src/data.txt"))....
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
假设我有一个字符串列表,我想通过过滤字符串列表过滤它们.对于包含以下内容的列表:"abcd","xcfg","dfbf"
我会精确列出过滤字符串:"a","b",以及像filter之后的东西(i-> i.contains(filterStrings)我想收到"abcd","dfbf"的列表,以及列表过滤字符串:"c","f"我想要列出"xcfg"和"dfbf"的列表.
List<String> filteredStrings = filteredStrings.stream()
.filter(i -> i.contains("c") || i.contains("f")) //i want to pass a list of filters here
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
有没有其他方法这样做而不是扩展lambda表达式的主体和编写一个带有标志的函数来检查每个过滤器?
java ×4
java-stream ×2
coding-style ×1
filter ×1
if-statement ×1
immutability ×1
integer ×1
java-8 ×1