Sorry for the simple question - I come from the .NET stack. All I want is an inline Predicate. Please tell me what I'm doing wrong:
toReturn = Iterables.find(articles, a -> a.toString().equals(input));
It tells me that 'a cannot be resolved to a variable'. I'm assuming that I just need an import or that I'm using an old version of Java? Thanks in advance!
What you're trying to do is not possible in Java 7 or earlier; it exists in Java 8 and later though. With Java 7 and prior you are able to use lambdaj to similar effect though. It would look something like this:
toReturn = Iterables.find(articles, new Predicate<Object>() {
public boolean apply(Object item) {
return item.toString().equals(input);
}
});
You can check out more details here.
Edit:
As pointed out in the comments, there are alternatives. As you're using Iterables I'm guessing you would want a com.google.common.base.Predicate which can be defined very similarly:
toReturn = Iterables.find(articles, new Predicate<Object>() {
public boolean apply(Object item) {
return item.toString().equals(input);
}
public boolean equals(Object obj) {
// check whether the other object is also a Predicate
}
});
Related
I'm new to Java and I can't understand why the IDE says that "Unexpected return value" inside the forEach where I declared that the boolean is true or false by an If statement.
My goal is to check that there is an object inside the "States" HashMap which already uses the name that I want to set to a new state. (The HashMap's key is a String which is called IdentifierOfState and the value is my State object which contains variables like its name.) Thank you for your help in advance!
public boolean isStateNameClaimed(String NameOfState)
{
States.forEach((IdentifierOfState, ValueOfState) ->
{
if (ValueOfState.getNameOfState().equalsIgnoreCase(NameOfState)) {return true;}
else {return false;}
});
return false;
}
The problem is that you are attempting to return the results in the wrong place. The {return true;} and {return true;} are in a lambda, so they are attempting to return a result for the lambda. But the inferred type signature for that lambda doesn't allow any values to be returned.
If your intention is that those return statements should be returning a result from isStateNameClaimed, then the better solution is to just use a for loop to iterate the elements of States.
It doesn't help things that your Java code contains a number of egregious Java style violations. You should NOT start the name of a variable with an upper-case letter. It will confuse ... and then annoy ... other people reading your code.
You may say: "Nah, I don't need to follow the rules, 'cos nobody else will be reading my code". But you are asking >>us<< to read your code.
I'm new to Java ...
... so NOW is the time to learn to do it correctly. Java style matters to people reading your code.
This is how I would write it in classic Java:
public boolean isStateNameClaimed(String name) {
for (State v: states.values()) {
if (v.getNameOfState().equalsIgnoreCase(name)) {
return true;
} else {
return false;
}
}
return false;
}
Or using streams:
public boolean isStateNameClaimed(String name) {
return states.values().stream().anyMatch(
(v) -> v.getNameOfState().equalsIgnoreCase(name));
}
Actually ... I just noticed that those two solutions are not equivalent. And based on your description of what you are trying to do, it probably means that the first one and your original attempt are algorithmically incorrect.
forEach will invoke a given callable function for every element. We can't have return value to that function.
Try using "filter" or assign result to local variable.
Return from lambda forEach() in java
I have some problems with using Optional.ifPresent statement. I would like to reduce number of NullPointerExceptions, so I decided to use Optional values.
Also I am trying to avoid a ladder of if statements anti-pattern.
So I implemented Optional.isPresent statement. But it's not really that what I expected.
Please look at these listings:
This is a part of my service:
if (getAllComputerProducers().isPresent()) {
if (isComputerProducerAlreadyExist(computerProducer))
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
computerProducerRepository.save(computerProducer);
return new ResponseEntity<>(HttpStatus.CREATED);
getAllComputerProducers function looks like that:
private Optional<List<ComputerProducer>> getAllComputerProducers() {
return Optional.ofNullable(computerProducerRepository.findAll());
}
As you can see, this function returns Optional of List.
The isComputerProducerAlreadyExist function is implemented like that:
private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer) {
return getAllComputerProducers()
.get()
.stream()
.anyMatch(producer -> producer.getProducerName()
.equalsIgnoreCase(computerProducer.getProducerName()));
}
It's so much code and I believe that it could be made simpler.
My target is to reduce code to one line command like:
getAllCimputerProducers().ifPresent(***and-here-some-anyMatch-boolean-function***)
but I can't insert there a function which returns something. How can I do it?
Regards to everyone :)
You could try something like
private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer){
return this.getAllComputerProducers()
.map((List<ComputerProducer> computerProducers) -> computerProducers.stream()
.anyMatch(producer -> producer.getProducerName().equalsIgnoreCase(computerProducer.getProducerName())))
.orElse(Boolean.FALSE);
}
Or instead of loading all computer producers load only the ones using its name.
private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer){
return computerProducerRepository.findByName(computerProducer.getProducerName()).isEmpty();
}
And as far as I know Spring supports also "exist" methods for repositories without even the need to load the Entity.
The following should work
Predicate<ComputerProducer> cpPredicate = producer -> producer.getProducerName()
.equalsIgnoreCase(computerProducer.getProducerName());
boolean compProdExists = getAllCimputerProducers()
.map(list -> list.stream()
.filter(cpPredicate)
.findFirst()))
.isPresent();
You can pass the computerProducer.getProducerName() to repository to get the existing record. Method name will be 'findByProducerName(String producerName)', if producerName has unique constraint, return type will be Optional<ComputerProducer>, else Optional<List<ComputerProducer>>. However, JPA returns empty list instead of null, so optional on list is not required.
I am very new to Java 8 features like streams, filters and stuff and the tell the truth, I haven't been writing in Java for more than a year.
Here is my problem if someone could give a suggestion .
#Override
public ArrayList<Agent> getAllEnabledAgents() throws Exception {
ArrayList<Agent> agents = repository.all(); //redis repository
Stream<Agent> result = agents.stream().filter(a-> a.equals(a.getConfigState().Enabled)); //enum
return result; //I dont know how to return result or whether I am using stream correctly.
}
The main idea is that I want return all enabled agents. gerConfigState() returns an enum (__ConfigState). not sure If am doing this correctly.
Use the collect-metod of the Stream. Also, your filter looks a bit strange, since the variable a is an object of class Agent.
So perhaps something like this:
agents.stream()
.filter(a -> a.getConfigState() == Enabled)
.collect(Collectors.toList());
Then again, like the comment states, you might just be better off filtering this with a query.
Your filter condition is not correct (I assume getConfigState() returns an enum). You can use something like below:
Stream<Agent> streamAgent = agents.stream().filter(a-> a.getConfigState() == Enabled);
return streamAgent.collect(Collectors.toList());
Thanks for the help. This is the final version:
#Override
public List<Agent> getAllEnabledAgents() throws Exception {
return repository.all()
.stream()
.filter(a-> a.getConfigState() == ConfigState.Enabled)
.collect(Collectors.toList());
}
I use a node.js package for "Bridge API to connect with existing Java APIs": node-java.
https://github.com/joeferner/node-java
One Java API function that I need to connect is
public void reqMktData(int tickerId, Contract contract,
String genericTicklist, boolean snapshot, List<TagValue> mktDataOptions)
{
m_s.reqMktData(tickerId, contract, genericTicklist, snapshot, mktDataOptions);
}
The problem is I don't know how to pass Java type List<> from node JavaScript. Int or boolean or others work fine.
So, here's my question.
What kind of type of values in JavaScript corresponds to JavaList<>?
Thanks.
In line with what #mstrthealias said, the example on the project's GitHub page says,
var list = java.newInstanceSync("java.util.ArrayList");
java.newInstance("java.util.ArrayList", function(err, list) {
if(err) { console.error(err); return; }
// new list
});
How do I code in Java the following python lines?
a = [True, False]
any (a)
all (a)
inb4 "What have you tried?"
The sledge-hammer way would be writing my own all and any methods (and obviously a class to host them):
public boolean any (boolean [] items)
{
for (boolean item: items)
if (item) return true;
return false;
}
//other way round for all
But I don't plan on re-inventing the wheel and there must be a neat way to do this...
any() is the same thing as Collection#contains(), which is part of the standard library, and is in fact an instance method of all Collection implementations.
There is no built-in all(), however. The closest you'll get, aside from your "sledgehammer" approach, is Google Guava's Iterables#all().
In Java 7 and earlier, there is nothing in the standard libraries for doing that.
In Java 8, you should be able to use Stream.allMatch(...) or Stream.anyMatch(...) for this kind of thing, though I'm not sure that this would be justifiable from a performance perspective. (For a start, you would need to use Boolean instead of boolean ...)
An example for Java 8 streaming API would be:
Boolean[] items = ...;
List<Boolean> itemsList = Arrays.asList(items);
if (itemsList.stream().allMatch(e -> e)) {
// all
}
if (itemsList.stream().anyMatch(e -> e)) {
// any
}
A solution with the third party library hamcrest:
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
if (everyItem(is(true)).matches(itemsList)) {
// all
}
if (hasItem(is(true)).matches(itemsList)) { // here is() can be omitted
// any
}