This question already has answers here:
How to negate a method reference predicate
(13 answers)
Closed 4 years ago.
Prior to Java 8, this method would be used to create a list of hidden files:
File[] hiddenFiles = new File("./directory/").listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isHidden();
}
});
In Java 8, this can be shortened to:
File[] hiddenFiles = new File("./directory/").listFiles(File::isHidden);
Returning non-hidden files in the original code was a trivial change: return file.!isHidden(); as a substitute for return file.isHidden();. I cannot recreate this functionality within a single line.
There is no isNotHidden function within the File class. Without creating one (or without deferring to the original, more verbose code), is there a way to recreate it using the new single-line style?
How about this,
File[] hiddenFiles = new File("c:/data").listFiles(f -> !f.isHidden());
Coming in java-11 Predicate.not, until then you can't via a method reference
Predicate.not(File::isHidden)
Related
This question already has an answer here:
Java 8 avoiding null pointer checks using Optional
(1 answer)
Closed 1 year ago.
I am having a small snippet of code. I would like to write it in a better way with fewer nested checks. How can I achieve it?
Item item = itemResponse.getItem();
Optional<Item> optionalItem = Optional.ofNullable(item);
if (optionalItem.isPresent()) {
List<NameValue> listValues = item.getValues();
Optional<List<NameValue>> optionalListValues = Optional.ofNullable(listValues);
if (optionalListValues.isPresent()) {
System.out.println(listValues);
}
}
Is there any concise way I can rewrite the above piece of code using Java 8?
You can make itemResponse.getItem() class to return Optional<Item> and use the chained map method which will executed only if Optional has value, and if map method return non null value then only final ifPresent(Consumer consumer) is executed
Optional<Item> item = itemResponse.getItem()
item.map(item::getValues)
.ifPresent(System.out::println);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a method that return an array of files in a given directory that is giving me a null pointer exception when executed. I can't figure out why.
private ArrayList<File> getFiles(String path) {
File f = new File(path);
ArrayList<File> files = new ArrayList<>(Arrays.asList(f.listFiles()));
return files;
}
thanks for your help
This NullPointerException is thrown when the path specified while initializing the file is incorrect (doesn't exist).
In such cases it is always advisable to add some null checks(protective code) in your method.
eg:
if( f != null) { //get the list of files }
may be casue by f.listFiles() return one null array.you can watch the variables in debug model
This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 6 years ago.
Is it possible to use String as a variable name.. like in this example -
String musicPlaying = "music2";
Music music1 = new Music("blaalla");
Music music2 = new Music("blalala");
Music music3 = new Music("balaada");
if(!musicPlaying.stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}
What you can do is by associating (mapping) those values to the Music object. Here is example:
Map<String, Music> musics = new HashMap<>();
String musicPlaying = "music2";
musics.put("music1", new Music("blaalla"));
musics.put("music2", new Music("blalala"));
musics.put("music3", new Music("balaada"));
if(!musics.get(musicPlaying).stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}
You can't do this in Java, but you can almost do it using a map.
Map<String, Music> map = new HashMap<String, Music>();
map.put("music1", music1);
map.put("music2", music2);
map.put("music3", music3);
if(map.get(musicPlaying).stillPlaying) {
// happy listening
}
No, this is not supported in Java.
stillPlaying doesn't exist as a method (or variable) on String.
As the comment suggests below, it probably is doable through some reflection, however to quote another comment...
You can do all kinds of stupid tricks with reflection. But you're
basically breaking the "warranty void if removed" sticker on the class
the instant you do it.
No. But you might want to look into using a Map instead.
I used a switch case.
Switch (string)
{
case "string1":
string1();
break;
case "string2":
string2();
break;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am developing a console application where I can register items. Each item has 3 properties serial number, model, year.
I have 3 classes Laptop, Laptops(arraylist) and Office to run the application.
So far I have managed to find the object itself by index number, but i need to list all objects with the property typed in.
This is how I ask user to choose the option
Laptops inHouse = new Laptops();
model = Console.askModel("Enter Model : ");
inHouse.findModel(model);
break;
That is the find method in Laptops class
public void findModel(String aModel)
{
int arraySize = laptops.size();
for(int i=0; i<arraySize; i++) {
if (laptops.get(i).getModel() == aModel) {
System.out.println(laptops.get(i));
}
}
}
this is the askModel method in Console class.
public static String askModel(String aModel)
{
System.out.println(aModel);
String model = askString("Enter the model: ");
return model;
}
Additionally, I am quite new to java, I understand the concept but still struggling on many thing so If I forgot to post a code which is needed to solve the problem I am sorry in advnace.
findModel is fine except for your String comparison which checks for object equality instead of String equality, change the comparison to:
if (laptops.get(i).getModel().equals(aModel))
For non-primitives, equality tests using == check if the object is literally identical (that it's the same instance), whereas String.equals will compare the actual String value.
You might want a HashMap instead of an ArrayList:
import java.util.HashMap
public class Laptops{
Map<String, Laptop> laptops = new HashMap<String, Laptop>();
//alternatively if java 7, do "= new HashMap<>();" instead
public Laptop findModel(Laptop aModel){
Laptop theModel = laptops.get(aModel);
return theModel;
}
To put the models in, you'll use the put method of HashMap:
public void addAModel(String modelName, Laptop aModel){
laptops.put(modelName, aModel);
}
This way if you know a model's name (a String), it will return you the Laptop object you're after.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying files from one directory to another in Java
I have a folder (c:/InstallationFiles) with .jar files in it. i want to read through it and if the name equals test1 i want to copy it to a test1 folder, then if the name is test2 copy it to a test2 folder etc. this is what i have so far:
private static int copyJARFiles() {
resultCode = 0;
File installFolder = new File(Constants.WINDOWS + Constants.INSTALLATION_FOLDER);
File[] installFiles = installFolder.listFiles();
for (int i = 0; i < installFiles.length; i++) {
if (installFiles[i].equals("test1.jar")){
}
if (installFiles[i].equals("test2.jar")){
}
}
return resultCode;
}
not sure how to copy it then. im still a rookie.
thank you / kind regards
if you want to copy jar:
You can use apache IO api. Use the below code:
FileUtils.copy(sourceFile,destinationFile);
You can also use java 7. It contains direct function to copy files.
if you want extract jar:
You can use java.util.zip.*; package classes.
Please let me know if you need more explanation.
Not sure I fully understood your task but maybe this example will help you
for (File f : installFolder.listFiles()) {
if (f.getName().endsWith(".jar")) {
File targetDir = new File(installFolder, f.getName().replace(".jar", ""));
if (!targetDir.exists()) {
targetDir.mkdir();
}
File target = new File(targetDir, f.getName());
Files.copy(f.toPath(), target.toPath());
}
}
The main idea is that Java 7 provides us with Files.copy util