C# .Take() in Java - java

I'm a C# Developer and recently starting get into Java development and here I have a question. Did Java have any build in method that doing the same thing with C# .Take()?
C# example:
int diffNo = 1;
someNumber.OrderBy(x => x.someNumber).Take(diffNo).ToList();
Java example:
someNumber.stream().sorted(Comparator.comparing(Object::getSomeNumber)).collect(Collectors.toList());
So now for Java part I only able to do sorting but don't know is there method can use to replace .Take()

Streams have a limit method, used to truncate a stream to up to the number of elements you provide as an argument.
So, assuming diffNo is a number, you can call it like this
someNumber.stream()
.sorted(Comparator.comparing(SomeClass::getSomeNumber))
.limit(diffNo)
.collect(Collectors.toList());

Related

How to use aggregateField() over multiple columns in Apache Beam Java SDK?

In Apache Beam Python SDK, it is possible to perform the following:
input
| GroupBy(account=lambda s: s["account"])
.aggregate_field(lambda x: x["wordsAddup"] - x["wordsSubtract"], sum, 'wordsRead')
How do we perform a similar action in the Java SDK? Strangely, the programming guide has only examples in Python for this transform.
Here is my attempt at producing the equivalent in Java:
input.apply(
Group.byFieldNames("account")
.aggregateField(<INSERT EQUIVALENT HERE>, Sum.ofIntegers(), "wordsRead"));
There are some Java examples at https://beam.apache.org/documentation/programming-guide/#using-schemas . (Note you may have to select the java tab on a selector that has both Java and Python to see them.)
In Java I don't think the first argument of aggregateField can take an arbitrary expression; it must be a field name. You can proceed the grouping operation with a projection that adds a new field for the desired expression. For example
input
.apply(SqlTransform.query(
"SELECT *, wordsAddup - wordsSubtract AS wordsDiff from PCOLLECTION")
.apply(Group.byFieldNames("account")
.aggregateField("wordsDiff", Sum.ofIntegers(), "wordsRead"));

How to pass and return AppleScript record with Java

Environment
Yosemite 10.10.3
Oracle Java 1.8
I have no problems passing and returning single arguments and list using the ScriptBinding hash.
Question: I don't see how to pass the equivalent of a AppleScript Record (e.g. {first: "Foo" last: "Bar"}) or, for that matter, receiving one back in Java.
OK, I found the answer by brute force:
To send the AppleScript the equivalent of a record, you can set the SimpleBinding "javax.script.argv" to a hash-map. There is a caveat that the keys in the hash-map can not be objects, for example {"arg1" 7, 8 [9])
To receive a record back from AppleScript, just return it from the script. It will be coerced to a hash-map.
I will test further and add any notable information as comments to this answer.

Java parallel execution on multicore

i would like to know whether exist a way to parallelize queries in Java (or there is framework or a library) like in C# and Linq:
var query = from item in source.AsParallel().WithDegreeOfParallelism(2)
where Compute(item) > 42
select item;
and if i can't parallelize queries if i can do something like this in c# (a for each parallelized) :
Parallel.ForEach(files, currentFile =>
{
// The more computational work you do here, the greater
// the speedup compared to a sequential foreach loop.
string filename = System.IO.Path.GetFileName(currentFile);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);
bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
bitmap.Save(System.IO.Path.Combine(newDir, filename));
// Peek behind the scenes to see how work is parallelized.
// But be aware: Thread contention for the Console slows down parallel loops!!!
Console.WriteLine("Processing {0} on thread {1}", filename,
Thread.CurrentThread.ManagedThreadId);
}
please if you post any framework or library, can you tell me the experience that you had with it ?
thx for your time.
about c# and linq you can find here the documentation : http://msdn.microsoft.com/en-us/library/dd997425.aspx
There isn't a direct translation. Firstly Java doesn't have LINQ nor does it have any standard parallel collection classes.
GPars is perhaps closest fit.
Note that while it is targeted at groovy it's API is perfectly usable from java
Maybe Fork/Join Framework can help you ? Here is java tutorial

Coverting string to java code

I have a string constructed at run time like
str = "a+dataValue(i)";
where 'a' is a variable, 'dataValue(i)' is a function with argument i
Now I have a function where I want to use string str as part of code. For example
public void func()
{
for(int i=0;i<n;i++)
Sytem.out.println(converted_to_java_source(str)); //(i.e.) a+dataValue(i); it should be converted at runtime not compile time
}
I need output like as follows:
when a = 2; dataValue(i) returns i; n = 5
On call to func it should print
2 3 4 5 6 7
Thank you.
You are looking for the Java equivalent of the eval function / method in dynamically typed languages like JavaScript, Perl, Python and so on. Unfortunately there isn't one.
There are various ways to do this kind of thing in Java, but they are all expensive, and come with a variety of other down-sides.
My advice is to look for another (easier / cheaper) way to meet your requirement.
If you really need to go down the eval route, then here are some related Q/A's which give a reasonable coverage of the options.:
Is there an eval() function in Java?
Is there a java equivalent of the python eval function?
You could take a look at the Byte Code Engineering Libraray (BCEL) or ASM. In either case, things can get messy and overcomplicated so I would recommend what Stephen suggested and try to look for another way.
You could, for instance, use som if else statements to call your function in the usual manner, maybe something like:
String functionName = "...";
if (functionName.toLowerCase().equals("someMethodName")
{
someMethodName(someParams);
}

Is there a Java equivalent of Python's printf hash replacement?

Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity).
# hash of values
vals = {}
vals['a'] = 'a'
vals['b'] = 'b'
vals['1'] = 1
output = sys.stdout
file = open(filename).read()
print >>output, file % vals,
So in the file there are %(a), %(b), %(1) etc that I want substituted with the hash keys. I perused the API but couldn't find anything. Did I miss it or does something like this not exist in the Java API?
You can't do this directly without some additional templating library. I recommend StringTemplate. Very lightweight, easy to use, and very optimized and robust.
I doubt you'll find a pure Java solution that'll do exactly what you want out of the box.
With this in mind, the best answer depends on the complexity and variety of Python formatting strings that appear in your file:
If they're simple and not varied, the easiest way might be to code something up yourself.
If the opposite is true, one way to get the result you want with little work is by embedding Jython into your Java program. This will enable you to use Python's string formatting operator (%) directly. What's more, you'll be able to give it a Java Map as if it were a Python dictionary (vals in your code).

Categories

Resources