Scala和Java代码的样本,Scala代码看起来更简单/行数更less?

我需要一些Scala和Java代码的示例代码(我也很好奇它们),它们表明Scala代码更简单,更简洁,然后用Java编写代码(当然,这两个示例都应该解决相同的问题)。

如果只有Scala样例,像“这是Scala中的抽象工厂,Java中它看起来更麻烦”,那么这也是可以接受的。

谢谢!

我喜欢大部分被接受和这个答案

让我们来改进堆栈器的例子,并使用Scala的案例类 :

case class Person(firstName: String, lastName: String) 

上面的Scala类包含下面的Java类的所有function, 还有一些 – 例如它支持模式匹配 (Java没有)。 Scala 2.8添加了命名参数和默认参数,这些参数用于为case类生成一个复制方法 ,它与以下Java类的with *方法具有相同的function。

 public class Person implements Serializable { private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Person withFirstName(String firstName) { return new Person(firstName, lastName); } public Person withLastName(String lastName) { return new Person(firstName, lastName); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Person person = (Person) o; if (firstName != null ? !firstName.equals(person.firstName) : person.firstName != null) { return false; } if (lastName != null ? !lastName.equals(person.lastName) : person.lastName != null) { return false; } return true; } public int hashCode() { int result = firstName != null ? firstName.hashCode() : 0; result = 31 * result + (lastName != null ? lastName.hashCode() : 0); return result; } public String toString() { return "Person(" + firstName + "," + lastName + ")"; } } 

那么,在使用我们(当然):

 Person mr = new Person("Bob", "Dobbelina"); Person miss = new Person("Roberta", "MacSweeney"); Person mrs = miss.withLastName(mr.getLastName()); 

反对

 val mr = Person("Bob", "Dobbelina") val miss = Person("Roberta", "MacSweeney") val mrs = miss copy (lastName = mr.lastName) 

我发现这个令人印象深刻

Java的

 public class Person { private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } 

斯卡拉

 class Person(val firstName: String, val lastName: String) 

以及这些(抱歉不粘贴,我不想偷代码)

  • 皇后问题的Java
  • 皇后问题斯卡拉

任务:编写一个程序来索引关键字列表(如书)。

说明:

  • input:列表<String>
  • 输出:Map <Character,List <String >>
  • 地图的关键是“A”到“Z”
  • 地图中的每个列表都被sorting。

Java的:

 import java.util.*; class Main { public static void main(String[] args) { List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer"); Map<Character, List<String>> result = new HashMap<Character, List<String>>(); for(String k : keywords) { char firstChar = k.charAt(0); if(!result.containsKey(firstChar)) { result.put(firstChar, new ArrayList<String>()); } result.get(firstChar).add(k); } for(List<String> list : result.values()) { Collections.sort(list); } System.out.println(result); } } 

斯卡拉:

 object Main extends App { val keywords = List("Apple", "Ananas", "Mango", "Banana", "Beer") val result = keywords.sorted.groupBy(_.head) println(result) } 

任务:

你有一个namePersonPerson的对象的列表。 你的任务是先按namesorting这个列表,然后按agesorting。

Java 7:

 Collections.sort(people, new Comparator<Person>() { public int compare(Person a, Person b) { return a.getName().compare(b.getName()); } }); Collections.sort(people, new Comparator<Person>() { public int compare(Person a, Person b) { return Integer.valueOf(a.getAge()).compare(b.getAge()); } }); 

斯卡拉:

 val sortedPeople = people.sortBy(p => (p.name, p.age)) 

更新

自从我写这个答案以来,已经有了一些进展。 lambda(和方法引用)最终落在了Java中,并且正在风靡Java世界。

这就是上面的代码看起来像Java 8 (由@fredoverflow贡献):

 people.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge)); 

虽然这段代码几乎一样短,但它的工作方式与Scala相比并不那么完美。

在Scala解决scheme中, Seq[A]#sortBy方法接受函数A => B ,其中B需要进行OrderingOrdering是一个types的类。 想两全其美:与Comparable ,对于所讨论的types是隐含的,但与Comparator类似,它是可扩展的,可以追溯地添加到没有它的types中。 由于Java缺lesstypes类,所以必须重复每一个这样的方法,一次是Comparable ,然后是Comparator 。 例如,请参阅comparing然后在此处 comparing

types类允许编写规则,例如“如果A具有sorting并且B具有sorting,则它们的元组(A,B)也具有sorting”。 在代码中,即:

 implicit def pairOrdering[A : Ordering, B : Ordering]: Ordering[(A, B)] = // impl 

这就是我们的代码中的sortBy可以按名称和年龄进行比较的方式。 那些语义将被编码上述“规则”。 一个Scala程序员会直觉地期望这样工作。 Ordering不需要添加comparing等特殊用途的方法。

Lambdas和方法引用只是函数式编程的冰山一angular。 🙂

任务:

你有一个XML文件“company.xml”,看起来像这样:

 <?xml version="1.0"?> <company> <employee> <firstname>Tom</firstname> <lastname>Cruise</lastname> </employee> <employee> <firstname>Paul</firstname> <lastname>Enderson</lastname> </employee> <employee> <firstname>George</firstname> <lastname>Bush</lastname> </employee> </company> 

您必须阅读此文件并打印所有员工的firstNamelastName字段。

Java: [从这里取出]

 import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XmlReader { public static void main(String[] args) { try { File file = new File("company.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("employee"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname"); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); System.out.println("First Name: " + ((Node) fstNm.item(0)).getNodeValue()); NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname"); Element lstNmElmnt = (Element) lstNmElmntLst.item(0); NodeList lstNm = lstNmElmnt.getChildNodes(); System.out.println("Last Name: " + ((Node) lstNm.item(0)).getNodeValue()); } } } catch (Exception e) { e.printStackTrace(); } } } 

斯卡拉: [从这里开始 ,幻灯片#19]

 import xml.XML object XmlReader { def main(args: Array[String]): Unit = { XML.loadFile("company.xml") match { case <employee> { employees @ _* } </employee> => { for(e <- employees) { println("First Name: " + (e \ "firstname").text) println("Last Name: " + (e \ "lastname").text) } } } } } 

[比尔编辑; 检查评论] –

嗯,如何做到这一点,而不回复在一个无格式的回复部分…哼。 我想我会编辑你的答案,让你删除它,如果它错误的你。

这是我将如何在Java中使用更好的库:

 public scanForEmployees(String filename) { GoodXMLLib source=new GoodXMLLib(filename); while( String[] employee: source.scanFor("employee", "firstname", "lastname") ) { System.out.println("First Name: " + employee[0]); System.out.println("Last Name: " + employee[1]); } } 

这只是一个不涉及魔法和所有可重用组件的快速入侵。 如果我想添加一些魔法,我可以做比返回一个string数组更好的东西,但即使这个GoodXMLLib是完全可重用的。 scanFor的第一个参数是该部分,所有将来的参数都是要查找的项目是有限的,但是界面可以稍微磨光以添加多级匹配而没有真正的问题。

我承认,Java总体上有一些相当差的库支持,但是来吧 – 比较Java十年(?)旧XML库的一个可怕的用法和基于简洁的实现的实现是不公平的,从语言的比较!

根据string执行的操作的映射。

Java 7:

 // strategy pattern = syntactic cruft resulting from lack of closures public interface Todo { public void perform(); } final Map<String, Todo> todos = new HashMap<String,Todo>(); todos.put("hi", new Todo() { public void perform() { System.out.println("Good morning!"); } } ); final Todo todo = todos.get("hi"); if (todo != null) todo.perform(); else System.out.println("task not found"); 

斯卡拉:

 val todos = Map( "hi" -> { () => println("Good morning!") } ) val defaultFun = () => println("task not found") todos.getOrElse("hi", defaultFun).apply() 

这一切都是在尽可能好的口味上完成的!

Java 8:

 Map<String, Runnable> todos = new HashMap<>(); todos.put("hi", () -> System.out.println("Good morning!")); Runnable defaultFun = () -> System.out.println("task not found"); todos.getOrDefault("hi", defaultFun).run(); 

我喜欢这个简单的sorting和转换例子,取自David Pollak的“Scala Beginning”一书:

在Scala中:

 def validByAge(in: List[Person]) = in.filter(_.valid).sortBy(_.age).map(_.first) case class Person(val first: String, val last: String, val age: Int) {def valid: Boolean = age > 18} validByAge(List(Person("John", "Valid", 32), Person("John", "Invalid", 17), Person("OtherJohn", "Valid", 19))) 

在Java中:

 public static List<String> validByAge(List<Person> in) { List<Person> people = new ArrayList<Person>(); for (Person p: in) { if (p.valid()) people.add(p); } Collections.sort(people, new Comparator<Person>() { public int compare(Person a, Person b) { return a.age() - b.age(); } } ); List<String> ret = new ArrayList<String>(); for (Person p: people) { ret.add(p.first); } return ret; } public class Person { private final String firstName; private final String lastName; private final Integer age; public Person(String firstName, String lastName, Integer age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirst() { return firstName; } public String getLast() { return lastName; } public Integer getAge() { return age; } public Boolean valid() { return age > 18; } } List<Person> input = new ArrayList<Person>(); input.add(new Person("John", "Valid", 32)); input.add(new Person("John", "InValid", 17)); input.add(new Person("OtherJohn", "Valid", 19)); List<Person> output = validByAge(input) 

我正在Scala写一个Blackjack游戏。 以下是我的dealerWins方法在Java中的外观:

 boolean dealerWins() { for(Player player : players) if (player.beats(dealer)) return false; return true; } 

以下是它在Scala中的外观:

 def dealerWins = !(players.exists(_.beats(dealer))) 

高级function的万岁!

Java 8解决scheme:

 boolean dealerWins() { return players.stream().noneMatch(player -> player.beats(dealer)); } 

我非常喜欢用户未知的 答案,所以我会尽力改进它。 下面的代码不是 Java示例的直接翻译,但它使用相同的API来完成相同的任务。

 def wordCount (sc: Scanner, delimiter: String) = { val it = new Iterator[String] { def next = sc.nextLine() def hasNext = sc.hasNextLine() } val words = it flatMap (_ split delimiter iterator) words.toTraversable groupBy identity mapValues (_.size) } 

我非常喜欢getOrElseUpdate方法,它在mutableMap中find并在这里显示,第一个Java,没有:

 public static Map <String, Integer> wordCount (Scanner sc, String delimiters) { Map <String, Integer> dict = new HashMap <String, Integer> (); while (sc.hasNextLine ()) { String[] words = sc.nextLine ().split (delimiters); for (String word: words) { if (dict.containsKey (word)) { int count = dict.get (word); dict.put (word, count + 1); } else dict.put (word, 1); } } return dict; } 

是的 – 一个WordCount,在这里在斯卡拉:

 def wordCount (sc: Scanner, delimiter: String) = { val dict = new scala.collection.mutable.HashMap [String, Int]() while (sc.hasNextLine ()) { val words = sc.nextLine.split (delimiter) words.foreach (word => dict.update (word, dict.getOrElseUpdate (word, 0) + 1)) } dict } 

这里是在Java 8中:

 public static Map<String, Integer> wordCount(Scanner sc, String delimiters) { Map<String, Integer> dict = new HashMap<>(); while (sc.hasNextLine()) { String[] words = sc.nextLine().split(delimiters); Stream.of(words).forEach(word -> dict.merge(word, 1, Integer::sum)); } return dict; } 

如果你想要100%的function:

 import static java.util.function.Function.identity; import static java.util.stream.Collectors.*; public static Map<String, Long> wordCount(Scanner sc, String delimiters) { Stream<String> stream = stream(sc.useDelimiter(delimiters)); return stream.collect(groupingBy(identity(), counting())); } public static <T> Stream<T> stream(Iterator<T> iterator) { Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, 0); return StreamSupport.stream(spliterator, false); } 

filtersort已经显示,但看看他们是如何轻松地与地图集成:

  def filterKeywords (sc: Scanner, keywords: List[String]) = { val dict = wordCount (sc, "[^A-Za-z]") dict.filter (e => keywords.contains (e._1)).toList . sort (_._2 < _._2) } 

这是一个非常简单的例子:方形整数,然后添加它们

 public int sumSquare(int[] list) { int s = 0; for(int i = 0; i < list.length; i++) { s += list[i] * list[i]; } return s; } 

在Scala中:

 val ar = Array(1,2,3) def square(x:Int) = x * x def add(s:Int,i:Int) = s+i ar.map(square).foldLeft(0)(add) 

压缩映射将该函数应用于数组的所有元素,因此:

 Array(1,2,3).map(square) Array[Int] = Array(1, 4, 9) 

向左折叠将从累加器开始,并将数组(i add(s,i)加到数组的所有元素(i)上,这样:

  Array(1,4,9).foldLeft(0)(add) // return 14 form 0 + 1 + 4 + 9 

现在可以进一步压缩到:

 Array(1,2,3).map(x => x * x ).foldLeft(0)((s,i) => s + i ) 

这一个我不会尝试Java(很多工作),把XML转换为一个地图:

 <a> <b id="a10">Scala</b> <b id="b20">rules</b> </a> 

另一个class轮从XML获取地图:

 val xml = <a><b id="a10">Scala</b><b id="b20">rules</b></a> val map = xml.child.map( n => (n \ "@id").text -> n.child.text).toMap // Just to dump it. for( (k,v) <- map) println(k + " --> " + v) 

如何Quicksort?


Java的

以下是一个通过谷歌searchfind的java例子,

该URL是http://www.mycstutorials.com/articles/sorting/quicksort

 public void quickSort(int array[]) // pre: array is full, all elements are non-null integers // post: the array is sorted in ascending order { quickSort(array, 0, array.length - 1); // quicksort all the elements in the array } public void quickSort(int array[], int start, int end) { int i = start; // index of left-to-right scan int k = end; // index of right-to-left scan if (end - start >= 1) // check that there are at least two elements to sort { int pivot = array[start]; // set the pivot as the first element in the partition while (k > i) // while the scan indices from left and right have not met, { while (array[i] <= pivot && i <= end && k > i) // from the left, look for the first i++; // element greater than the pivot while (array[k] > pivot && k >= start && k >= i) // from the right, look for the first k--; // element not greater than the pivot if (k > i) // if the left seekindex is still smaller than swap(array, i, k); // the right index, swap the corresponding elements } swap(array, start, k); // after the indices have crossed, swap the last element in // the left partition with the pivot quickSort(array, start, k - 1); // quicksort the left partition quickSort(array, k + 1, end); // quicksort the right partition } else // if there is only one element in the partition, do not do any sorting { return; // the array is sorted, so exit } } public void swap(int array[], int index1, int index2) // pre: array is full and index1, index2 < array.length // post: the values at indices 1 and 2 have been swapped { int temp = array[index1]; // store the first value in a temp array[index1] = array[index2]; // copy the value of the second into the first array[index2] = temp; // copy the value of the temp into the second } 

斯卡拉

一个Scala版本的快速尝试。 打开代码改进者的季节; @)

 def qsort(l: List[Int]): List[Int] = { l match { case Nil => Nil case pivot::tail => qsort(tail.filter(_ < pivot)) ::: pivot :: qsort(tail.filter(_ >= pivot)) } } 

问题:你需要devise一个方法来asynchronous执行任何给定的代码。

Java解决scheme:

 /** * This method fires runnables asynchronously */ void execAsync(Runnable runnable){ Executor executor = new Executor() { public void execute(Runnable r) { new Thread(r).start(); } }; executor.execute(runnable); } ... execAsync(new Runnable() { public void run() { ... // put here the code, that need to be executed asynchronously } }); 

斯卡拉同样的事情(使用演员):

 def execAsync(body: => Unit): Unit = { case object ExecAsync actor { start; this ! ExecAsync loop { react { case ExecAsync => body; stop } } } } ... execAsync{ // expressive syntax - don't need to create anonymous classes ... // put here the code, that need to be executed asynchronously } 

Michael Nygard在FaKods 发布的断路器模式( link to code )

在Scala中实现如下所示:

 . . . addCircuitBreaker("test", CircuitBreakerConfiguration(100,10)) . . . class Test extends UsingCircuitBreaker { def myMethodWorkingFine = { withCircuitBreaker("test") { . . . } } def myMethodDoingWrong = { withCircuitBreaker("test") { require(false,"FUBAR!!!") } } } 

我认为这是非常好的。 它看起来只是一种语言的瑕疵,但它是CircuitBreaker对象中的一个简单的混合。

 /** * Basic MixIn for using CircuitBreaker Scope method * * @author Christopher Schmidt */ trait UsingCircuitBreaker { def withCircuitBreaker[T](name: String)(f: => T): T = { CircuitBreaker(name).invoke(f) } } 

谷歌提供的其他语言的“断路器”+您的语言。

为什么以前没有人发布过

Java的:

 class Hello { public static void main( String [] args ) { System.out.println("Hello world"); } } 

116个字符。

斯卡拉:

 object Hello extends App { println("Hello world") } 

56个字符。

我正在准备一个文档,它提供了几个Java和Scala代码的例子,只使用简单的Scala特性:

斯卡拉:一个更好的Java

如果您想要我添加一些内容,请回复评论。

懒洋洋地评估无限stream是一个很好的例子:

 object Main extends Application { def from(n: Int): Stream[Int] = Stream.cons(n, from(n + 1)) def sieve(s: Stream[Int]): Stream[Int] = Stream.cons(s.head, sieve(s.tail filter { _ % s.head != 0 })) def primes = sieve(from(2)) primes take 10 print } 

这是一个在Java中处理无限stream的问题: 是一个无限的迭代器坏devise?

另一个很好的例子是头等function和closures:

 scala> def f1(w:Double) = (d:Double) => math.sin(d) * w f1: (w: Double)(Double) => Double scala> def f2(w:Double, q:Double) = (d:Double) => d * q * w f2: (w: Double,q: Double)(Double) => Double scala> val l = List(f1(3.0), f2(4.0, 0.5)) l: List[(Double) => Double] = List(<function1>, <function1>) scala> l.map(_(2)) res0: List[Double] = List(2.727892280477045, 4.0) 

Java不支持头等function,而使用匿名内部类模仿闭包不是很优雅。 这个例子的另一个例子显示,java不能做的是从解释器/ REPL运行代码。 我发现这对于快速testing代码片段非常有用。

这个Scala代码

 def partition[T](items: List[T], p: (T, T) => Boolean): List[List[T]] = { items.foldRight[List[List[T]]](Nil)((item: T, items: List[List[T]]) => items match { case (first :: rest) :: last if p (first, item) => (List(item)) :: (first :: rest) :: last case (first :: rest) :: last => (item :: first :: rest) :: last case _ => List(List(item)) }) } 

如果可能的话,在Java中是完全不可读的。