I'm trying to use the .stream operator to find an object within a List<> but getting a syntax error I cant resolve despite following the examples I find on the net...hopefully someone can help with whatever I'm not understanding.
I set up the following as the object to be stored in a List<>:
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class JelCodeMapping {
private String jelCodeId;
private String jelCodeName;
private int network1;
private int network2;
private int network3;
}
Then instantiate a list (it gets populated elsewhere)
private List<JelCodeMapping> jelCodeMappings;
I then want to search for an object within the list which contains a particular value:
private List<Integer> getNetworksForJelCode(String jelCode) {
JelCodeMapping jelCodeMaping = jelCodeMappings.stream().filter(mapping -> mapping.getJelCodeId().equals(jelCode));
List<Integer> jelCodeNetworks = new ArrayList<>();
// other stuff happens here
return jelCodeNetworks;
}
but the line where I'm using the .stream() operator generates the following syntax error message:
Incompatible Types
Required: <packagePath>.JelCodeMapping
Found: java.util.stream.Stream <packagePath>.jelCodeMapping
I'm fairly sure I'm following the examples I've found, but cant resolve the issue. What am I not understanding?
Thanks for any thoughts/insights
3 Answers 3
You have to add a terminal operation to the stream.
For example
JelCodeMapping jelCodeMaping = jelCodeMappings.stream()
.filter(mapping -> mapping.getJelCodeId().equals(jelCode))
.findFirst()
.orElseThrow(() -> new RuntimeException(
"JelCodeMapping not found: " + jelCode));
See also the documentation for streams and in particular filter, findFirst or findAny.
The "Incompatible Types" error is because filter(Predicate) returns a Stream. The Stream can't be assigned to the JelCodeMapping variable.
The find methods return an optional and the orElseThrow methods will either return the optional value if present or throw the exception.
1 Comment
William's answer is to the point.
With Java 9 and above, you can also use dropWhile and findFirst (This is an equivalent alternative).
jelCodeMappingList.stream().dropWhile(jelCodeMapping -> !jelCodeMapping.equals("ID")).findFirst()
If the list might have multiple elements with same ID, you can use
jelCodeMappingList.stream().collect(Collectors.filtering(jelCodeMapping -> jelCodeMapping.getJelCodeId().equals("ID"),Collectors.toList()));
which returns you a list of JelCodeMapping with same ID.
Comments
Maybe you need a collect(), and make sure that there is someone whose jelCodeId equals with jelCode in jelCodeMappings;
List<JelCodeMapping> jelCodeMaping =
jelCodeMappings.stream()
.filter(mapping -> mapping.getJelCodeId().equals(jelCode))
.collect(Collectors.toList());
filter()returns?