Scala和Java代码示例,其中Scala代码看起来更简单/行数更少?

Scala和Java代码示例,其中Scala代码看起来更简单/行数更少?,java,scala,comparison,language-features,Java,Scala,Comparison,Language Features,我需要一些Scala和Java代码的代码示例(我也很好奇),这些示例表明Scala代码比Java编写的代码更简单和简洁(当然,两个示例应该解决相同的问题) 如果只有Scala示例带有类似“这是Scala中的抽象工厂,在Java中看起来会更麻烦”这样的注释,那么这也是可以接受的 谢谢 我最喜欢所有被接受的答案,我觉得这个答案给人留下了深刻的印象 爪哇 斯卡拉 和这些一样(很抱歉没有粘贴,我不想偷代码) 延迟计算的无限流就是一个很好的例子: object Main extends Applic

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

如果只有Scala示例带有类似“这是Scala中的抽象工厂,在Java中看起来会更麻烦”这样的注释,那么这也是可以接受的

谢谢


我最喜欢所有被接受的答案,我觉得这个答案给人留下了深刻的印象

爪哇

斯卡拉

和这些一样(很抱歉没有粘贴,我不想偷代码)


延迟计算的无限流就是一个很好的例子:

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中处理无限流的问题:

另一个很好的例子是第一类函数和闭包:

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)
scala>def1(w:Double)=(d:Double)=>math.sin(d)*w
f1:(w:Double)(Double)=>Double
scala>deff2(w:Double,q:Double)=(d:Double)=>d*q*w
f2:(w:Double,q:Double)(Double)=>Double
scala>vall=List(f1(3.0),f2(4.0,0.5))
l:List[(双精度)=>Double]=列表(,)
scala>l.map(2))
res0:List[Double]=List(2.727892280477045,4.0)
Java不支持第一类函数,用匿名内部类模仿闭包也不是很优雅。这个示例显示java不能做的另一件事是从解释器/REPL运行代码。我发现这对于快速测试代码片段非常有用。

让我们改进并使用Scala的:

上面的Scala类包含下面Java类的所有特性,以及其他一些特性——例如它支持的特性(Java没有)。Scala 2.8添加了命名参数和默认参数,用于生成for case类,这与下面Java类的with*方法具有相同的功能

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 + ")";
    }
}
然后,在使用中,我们(当然)有:

反对

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

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


    public int sumSquare(int[] list) {
        int s = 0;
        for(int i = 0; i < list.length; i++) {
            s += list[i] * list[i]; 
        }
        return s;
    }
Compact map将函数应用于数组的所有元素,因此:

Array(1,2,3).map(square)
Array[Int] = Array(1, 4, 9)
向左折叠将以0作为累加器开始,并将
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>

斯卡拉
规则
另一个从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)

val xml=Scalarules
val map=xml.child.map(n=>(n\“@id”).text->n.child.text.toMap
//只是想把它扔掉。
对于((k,v)快速排序怎么样


JAVA 下面是一个通过谷歌搜索找到的java示例

网址是

public void快速排序(int数组[])
//pre:数组已满,所有元素都是非空整数
//post:数组按升序排序
{
快速排序(array,0,array.length-1);//对数组中的所有元素进行快速排序
}
公共void快速排序(int数组[],int开始,int结束)
{
int i=start;//从左向右扫描的索引
int k=end;//从右向左扫描的索引
if(end-start>=1)//检查是否至少有两个元素要排序
{
int pivot=array[start];//将pivot设置为分区中的第一个元素
while(k>i)//当从左到右的扫描索引没有满足时,
{
(array[i]pivot&&k>=start&&k>=i)//从右侧查找第一个
k--;//元素不大于轴
if(k>i)//如果左seekindex仍然小于
swap(array,i,k);//在正确的索引中,交换相应的元素
}
swap(array,start,k);//索引交叉后,交换索引中的最后一个元素
//带枢轴的左分区
快速排序(数组,开始,k-1);//对左侧分区进行快速排序
快速排序(数组,k+1,end);//对右侧分区进行快速排序
}
else//如果分区中只有一个元素,则不要进行任何排序
{
return;//数组已排序,因此退出
}
}
公共无效交换(int数组[],int索引1,int索引2)
//前置:数组已满且index1、index2

斯卡拉 Scala版本的快速尝试。代码改进者的开放季节;@)

def qsort(l:List[Int]):List[Int]={
我匹配{
案例Nil=>Nil
案例透视::tail=>qsort(tail.filter(>=pivot))
}
}

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

说明:

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)
}
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))
  • 输入:列表
  • 输出:地图
  • 地图的关键是“A”到“Z”
  • 地图中的每个列表都已排序
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)
}
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))

我喜欢这个简单的排序和转换示例,摘自David Pollak的《Scala入门》一书:

在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)
publicstaticlist-validbage(列表中){
List people=new ArrayList();
用于(人员p:in){
如果(p.valid())人。添加(p);
}
Collections.sort(人,新的Comparator(){
公共整数比较(人员a、人员b){
返回a.age()-b.age();
} 
} );
List ret=new ArrayList();
用于(人员p:人员){
重新添加(第一页);
}
返回ret;
}
公共阶层人士{
私有最终字符串名;
私有最终字符串lastName;
私人最终整数年龄;
公众人物(字符串firstName,字符串lastNam)
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)
/**
* 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    
}
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))
  })
}
class Hello {
     public static void main( String [] args ) {
          System.out.println("Hello world");
     }
}
object Hello extends App {
     println("Hello world")
}
// 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()
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();
<?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>
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();
    }
  }
}
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)
        } 
      }
    }
  }
}
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]);
    }
} 
. . .
addCircuitBreaker("test", CircuitBreakerConfiguration(100,10))
. . .


class Test extends UsingCircuitBreaker {
  def myMethodWorkingFine = {
    withCircuitBreaker("test") {
      . . .
    }
  }

  def myMethodDoingWrong = {
    withCircuitBreaker("test") {
      require(false,"FUBAR!!!")
    }
  }
}
/**
 * Basic MixIn for using CircuitBreaker Scope method
 *
 * @author Christopher Schmidt
 */
trait UsingCircuitBreaker {
  def withCircuitBreaker[T](name: String)(f: => T): T = {
    CircuitBreaker(name).invoke(f)
  }
}
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;
}
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
}
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;
}
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);
}
    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)
    } 
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)
}
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))
people.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
implicit def pairOrdering[A : Ordering, B : Ordering]: Ordering[(A, B)] = // impl
boolean dealerWins() {
    for(Player player : players)
        if (player.beats(dealer))
            return false;
    return true;
}
def dealerWins = !(players.exists(_.beats(dealer)))
boolean dealerWins() {
    return players.stream().noneMatch(player -> player.beats(dealer));
}