return method refference to stream - java

I have a class Care
class Car{
private int wheels;
private int doors;
...
public int getWheels(){ return wheels;}
public int getDoors(){ return doors:}
}
And I have a collection of the cars
List<Car> cars = ...
I want to calculate the average numbers of doors and windows in the collection. I could do this:
cars.stream().mapToInt(Car::getWheels).avg().orElse(0.0)
cars.stream().mapToInt(Car::getDoors).avg().orElse(0.0)
However, I want to create a dynamic function for this, for example:
public double calculateAvgOfProperty(List<Car> cars, String property){
Function<Car,Integer> mapper = decideMapper(property);
return cars.stream().maptoInt(mapper).avg().orElse(0.0);
}
public Function<Car,Integer> decideMapper(String ppr){
if( ppr.equals("doors") return Car::getDoors;
if( ppr.equals("wheels") return Car::getWheels;
}
However, .mapToInt() requires ToIntFunction<? super T> mapper as argument, but the method reference is Function<Car,Integer>, and casting does not work.
However when I directly pass the method reference, for example .mapToInt(Car::getDoors), it works.
How to cast correctly cast Function<Car,Integer> to required type then?

You should not cast a Function to a ToIntFunction as they are not associated (ToIntFunction does not extend Function). They are however both functional interfaces, so the method reference can also be inferred directly as a ToIntFunction.
There is an average() method defined in IntStream:
public double calculateAvgOfProperty(List<Car> cars, String property) {
ToIntFunction<Car> mapper = decideMapper(property);
return cars.stream().mapToInt(mapper).average().orElse(0.0);
}
public ToIntFunction<Car> decideMapper(String ppr){
if( ppr.equals("doors")) return Car::getDoors;
if( ppr.equals("wheels")) return Car::getWheels;
...
}

Do you mean to create a method like this:
private double calculateAvgOfProperty(List<Car> cars, Function<Car, Integer> function) {
return cars.stream().mapToDouble(function::apply)
.average()
.orElse(0.0);
}
and then you can only call:
double r1 = calculateAvgOfProperty(cars, Car::getWheels);
double r2 = calculateAvgOfProperty(cars, Car::getDoors);
I don't understand very well your question, but you can replace mapToDouble with mapToInt if you want.

I'm not sure what you're trying to achieve, but I'm sure, that you have quite a few compile time errors in your code:
Missing some closing braces in the decideMapper method;
You don't really return anything for the default case, from decideMapper;
calling some .avg() on IntStream, which is not available.

Related

Parameterize a class with one of a fixed set of types

Say I have a generic class Foo which can hold an object of type T. Furthermore, let's say I only want to be able to instantiate the class with objects that are one of two types. Finally, let's say that the lowest common upper bound of these two types is a type that has many more subclasses than those two types that I want to allow, so I can't simply specify an upper bound for the type parameter (as in class Foo<T extends Something>), because then I would allow to instantiate the class with other types than the two I expect.
For illustration, let's say I want Foo to hold only either a String or an Integer. The lowest common upper bound is Object, so specifying an upper bound won't do the trick.
Certainly, I could do something along the lines of
class Foo<T> {
private T obj;
public Foo(T obj) throws IllegalArgumentException {
if (!(obj instanceof String || obj instanceof Integer)) {
throw new IllegalArgumentException("...");
}
this.obj = obj;
}
}
However, in this case, I can still call the constructor with any object; if I try to instantiate it with something that is neither a String nor an Integer, I will get an exception at runtime.
I would like to do better. I would like the compiler to infer statically (i.e., at compile time) that I can only instantiate this class with objects that are either String or Integer.
I was thinking something along those lines might do the trick:
class Foo<T> {
private T obj;
public Foo(String s) {
this((T) s);
}
public Foo(Integer i) {
this((T) i);
}
private Foo(T obj) {
this.obj = obj;
}
}
This works, but it looks really, really odd. The compiler warns (understandably) about unchecked casts. Of course I could suppress those warnings, but I feel this is not the way to go. In addition, it looks like the compiler can't actually infer the type T. I was surprised to find that, with the latter definition of class Foo, I could do this, for instance:
Foo<Character> foo = new Foo<>("hello");
Of course, the type parameter should be String here, not Character. But the compiler lets me get away with the above assignment.
Is there a way to achieve what I want, and if yes, how?
Side question: why does the compiler let me get away with the assignment to an object of type Foo<Character> above without even so much as a warning (when using the latter definition of class Foo)? :)
Try using static factory method to prevent compiler warning.
class Foo<T> {
private T obj;
public static Foo<String> of(String s) {
return new Foo<>(s);
}
public static Foo<Integer> of(Integer i) {
return new Foo<>(i);
}
private Foo(T obj) {
this.obj = obj;
}
}
Now you create instance using:
Foo<String> foos = Foo.of("hello");
Foo<Integer> fooi = Foo.of(42);
Foo<Character> fooc = Foo.of('a'); // Compile error
However the following are still valid since you can declare a Foo of any type T, but not instantiate it:
Foo<Character> fooc2;
Foo<Character> fooc3 = null;
Foo<Object> fooob1;
Foo<Object> fooob2 = null;
one word: interface. You want your Z to wrap either A or B. Create an interface implementing the smallest common denominator of A and B. Make your A and B implement that interface. There's no other sound way to do that, AFAIK. What you already did with your constructors etc. is the only other possibility, but it comes with the caveats you already noticed (having to use either unchecked casts, or static factory wrappers or other code smells).
note: If you can't directly modify A and/or B, create wrapper classes WA and WBfor them beforehand.
example:
interface Wrapper {
/* either a marker interface, or a real one - define common methods here */
}
class WInt implements Wrapper {
private int value;
public WInt( int value ) { this.value = value; }
}
class WString implements Wrapper {
private String value;
public WString( String value ) { this.value = value; }
}
class Foo<T> {
private Wrapper w;
public Foo(Wrapper w) { this.w = w; }
}
because you call your private Foo(T obj) due to diamond type inference. As such, it's equal to calling Foo<Character> foo = new Foo<Character>("hello");
Long story short: You are trying to create a union of two classes in java generics which is not possible but there are some workarounds.
See this post
Well the compiler uses the Character class in T parameter. Then the String constructor is used where String is casted to T (Character in this case).
Trying to use the private field obj as a Character will most likely result in an error as the saved value is an instance of the final class String.
Generics is not suitable here.
Generics are used when any class can be used as the type. If you only allow Integer and String, you should not use generics. Create two classes FooInteger and FooString instead.
The implementations should be pretty different anyway. Since Integers and Strings are very different things and you would probably handle them differently. "But I am handling them the same way!" you said. Well then what's wrong with Foo<Double> or Foo<Bar>. If you can handle Integer and String with the same implementation, you probably can handle Bar and Double and anything else the same way as well.
Regarding your second question, the compiler will see that you want to create a Foo<Character>, so it tries to find a suitable overload. And it finds the Foo(T) overload to call, so the statement is perfectly fine as far as the compiler is concerned.

Can I have function types in Java's Enum like Swift?

Is it possible to write an equivalent code in Java for the following swift code? In fact, I want to know if it's possible to have a case of functions inside Java's enum (X, Y in MyEnum)
enum MyEnum{
case X((Int) -> String)
case Y((Double) -> Int)
}
No, you can't; at least, not if you want the differing types to be available when you use the enum. All enum values have to have the same type.
When you want "enum" values to have heterogenous types, you could use a class with static final fields:
final class MyHeterogeneousEnum {
private MyHeterogeneousEnum() {} // Not instantiable.
static final Function<Integer, String> X = ...;
static final Function<Double, Integer> Y = ...;
}
which allows you to use the values with their full type information:
String s = MyHeterogeneousEnum.X.apply(123);
Integer i = MyHeterogeneousEnum.Y.apply(999.0);
Of course, you don't have useful methods like name(), or values() to iterate over the constants in this class, nor is it inherently serializable. You can make implement these yourself - but for values() you have to use wildcards in the return type, in order that all values can be returned:
static Iterable<Function<?, ?>> values() {
return Collections.unmodifiableList(Arrays.asList(X, Y));
}
However, note that a Function with a wildcard input type parameter is pretty much useless: you can't actually pass anything into it (other than null); so the values() method has limited utility.
It is possible (technically), but it might not be that useful, as creating a simple class, that consumes a Function instance.
As you might already know, in Java, the enums represent one or more constants of the same type, which could have their own properties - this include java.util.Function instances. However, these Function instances cannot be passed dynamically at Runtime, but should be rather set at compile time, so that the constant is created.
Of course, you could make each enum constant have a different typed Function, by just creating the enum's constructor Generic:
enum MyEnum {
X((String x) -> "Hello"), Y((Double d) -> 1);
Function<?, ?> function;
MyEnum(Function<?, ?> function) {
this.function = function;
}
}
This, however, is not quite useful (although it compiles just fine). The Function in X doesn't use it's String parameter and returns a fixed value. So does the one in Y.
I'd rather introduce two separate instances of the same class:
class Instance<T, U> {
private Function<T, U> function;
public Instance(Function<T, U> function) {
this.function = function;
}
}
This will allow you to dynamically pass a Function instance, instead of setting it at compile-time.
Yes for sure you can, in java enums can be more that just constants... every one of it values can be an anonymous class (take a look to TimeUnit.class for example)
now, you can do somthing like:
interface IFunction {
double getY(double x);
}
enum Function implements IFunction {
LINE {
#Override
public double getY(double x) {
return x;
}
},
SINE {
#Override
public double getY(double x) {
return Math.sin(x);
}
}
}
and then the implementation
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(Function.LINE.getY(i));
System.out.println(Function.SINE.getY(i));
}
}

Why do I get a compilation error when I try to have two methods with the same name and parameter type?

If i change the byte to int I get a compiler error. Could you explain the problem?
public class A {
protected int xy(int x) { return 0; }
}
class B extends A {
protected long xy(int x) { return 0; } //this gives compilor error
//protected long xy(byte x) { return 0; } // this works fine
}
If i change the byte to int I get a compiler error.
If you do that, you have this:
public class A {
protected int xy(int x) { return 0; }
}
class B extends A {
protected long xy(int x) { return 0; }
}
...and the only difference in the xy methods is their return type. Methods cannot be differentiated solely by their return types, that's the way Java is defined. Consider this:
myInstance.xy(1);
Which xy should that call? long xy(int x) or int xy(int x)?
If your goal is to override xy in B, then you need to make its return type int in order to match A#xy.
You can't have two methods with same signature in a Class though the methods are placed separately in different classes in the same inheritance tree. i.e. Base class and sub class
Note : Just return types can't make the compiler understand the difference in methods. return type is NOT included in the method signature as well
You are trying to write two methods with the same name and input parameters, that is not possible.
Look at the following two methods:
float met(){
return 4.5;
}
double met(){
return 5.4;
}
If we would write this line then
int x = (int)met();
what method would be called?
It is not possible to decide, therefore this situation is not permitted.
That's because if You change byte to int You will have method with the same signature in base and sub class (same method name and parameter type) and therefore return type should be the same as well. Because is not (int and long) it will give You error
You can differentiate methods by parameters and names only.
both methods are in same class B
b.xy(byte x) or b.xy(int x) is called for input xy(0) or xy(1)
Overiding method should return a type that can be substituted for the type returned by overriden method
Because when you change the byte into int the Instance which calls the method doesn't know which method is meant. The overwritten one or the old one?
Thats why it's not allowed to have the same signatures (method name, type of parameters and amount of parameters). Just as an information: The return type is not part of the signature.

How do I bound a generic type to 2 types that are almost completely separated in hierarchy

How do I do this? Because you can only extend one class so it can only have one upper bound.
In my case I need the generic type to be bounded in String and int. If I use an Integer wrapper instead of int and rely on auto-boxing, I can make it but the problem is other classes can be passed as a type parameter as well.
What's the best way to do this?
You could use the non generic variants of collections (e.g List), or
more cleanly explicitly List<Object> to show code's intention.
Wrap that in a MyList class, and create add(), get() methods for each type you want to support:
add(Integer elem);
add(String elem);
But Object get() cannot be typed, such that it makes sense.
So finally you also can use Object with List, and omit the wrapper.
I don't think you can do it. String also is a final class and all that stuff. As #NimChimpsky said, you are probably better using Object itself. Another solution is a wrapper for both classes, but you will still have a resulting object which you will probably need to cast around and rely on instanceof:
class StringInt {
private String string;
private Integer integer;
public StringInt(String s) { this.string = s; }
public StringInt(Integer i) { this.integer = i; }
public Object getValue() { return string != null ? string : integer; }
}
Or with an ugly verification, which, obviously, will only apply at runtime...
class StringIntGen<T> {
private T t;
public StringIntGen(T t) {
if (!(t instanceof String) && !(t instanceof Integer))
throw new IllegalArgumentException(
"StringIntGen can only be Integer or String");
this.t = t;
}
public T getValue() { return t; }
}

Dynamic casting in Java

Before I get chided for not doing my homework, I've been unable to find any clues on the multitude of questions on Java generics and dynamic casting.
The type Scalar is defined as follows:
public class Scalar <T extends Number> {
public final String name;
T value;
...
public T getValue() {
return value;
}
public void setValue(T val) {
this.value = val;
}
}
I would like to have a method that looks like this:
public void evilSetter(V val) {
this.value = (T) val;
}
Sure, this is generally discouraged. The reason I want such a method is because I have a collection of Scalars whose values I'd like to change later. However, once they go in the collection, their generic type parameters are no longer accessible. So even if I want make an assignment that's perfectly valid at runtime, there's no way of knowing that it'll be valid at compile time, with or without generics.
Map<String, Scalar<? extends Number>> scalars = ...;
Scalar<? extends Number> scalar = scalars.get("someId");
// None of this can work
scalar.value = ...
scalar.setValue(...)
So how do I implement a checked cast and set method?
public <V extends Number> void castAndSet(V val) {
// One possibility
if (this.value.getClass().isAssignableFrom(val.getClass()) {
// Some cast code here
}
// Another
if (this.value.getClass().isInstanceOf(val) {
// Some cast code here
}
// What should the cast line be?
// It can't be:
this.value = this.value.getClass().cast(val);
// Because this.value.getClass() is of type Class<?>, not Class<T>
}
So I'm left with using
this.value = (T) val;
and catching a ClassCastException?
You have:
this.value.getClass().isAssignableFrom(val.getClass())
This is probably going to be a problem unless you can be certain value will never be null.
You also have:
this.value = (T) val;
This will only cast to Number and not to T because under the hood T is just a Number due to type-erasure. Therefore if value is a Double and val is an Integer, no exception will be thrown.
If you actually want to perform a checked cast, you must have the correct Class<T> object. This means you should be passing Class<T> in the constructor of your object. (Unless you can be sure value is never null, in which case you can go with your first idea.) Once you have that object (stored in a field), you can perform the checked cast:
T value = valueClass.cast(val);

Categories