1. 程式人生 > 實用技巧 >Java系列整理---Python Java Scala 區別

Java系列整理---Python Java Scala 區別

  本文僅從語法知識點上闡述三者之間的區別,因為該三種語言在現在工作中處理大資料時用的較多,簡單記錄一下,並逐步豐富與鞏固

1.基本資料結構用法

1.1 Array 陣列

I. Python

    主要是見於Numpy,同時Pandas中的DataFrame一起處理資料

II.Java

III.Scala

1.2 List 列表

I. Python

II.Java

III.Scala

1.3 Set集合

I. Python

II.Java

III.Scala

1.4 Dict字典、Map對映

I. Python

II.Java

III.Scala

Java的List、Set、Map

class TestDataStruct {
    //    List<T>, ArrayList<T>;
    //    Set<E>, HashSet<T>
    //    Map<String, T>, HashMap<String, T>
    public void testList() {
        List<String> list = new ArrayList<String>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        System.out.println(list);
        for(String sss: list) {
            System.out.println(sss);
        }
        System.out.println(list.contains("aaa"));
        Boolean s1 = list.remove("aaa");
        String s2 = list.remove(0);
        System.out.println(list);
    }

    public void testSet() {
        Set<String> set = new HashSet<String>();
        set.add("aaa");
        set.remove("aaa");
        set.add("bbb");
        for(String sss: set) {
            System.out.println(sss);
        }
    }

    public void testMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("aaa", "111");
        map.put("bbb", "222");
        map.remove("aaa");
        for(Map.Entry<String, Object> entry: map.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
    }
}

Scala的List、Set、Map

其中Scala的可以來源於java包,或來自scala.collection.mutable

class testBaseDataStruct {

  def testList(): Unit={
    var list1:List[String] = List[String]("111", "222")
    list1 :+= "ddd"
    list1 :+= "ccc"

    list1.foreach((item: String) => println(item))
    println(list1.drop(2))

    var list:util.List[String] = new util.ArrayList[String]()
    list.add("aaa");
    list.add("bbb");
    list.forEach((item: String) => println(item))

  }

  def testSet(): Unit={
    var set: Set[String] = Set[String]("###", "222")
    set += ("aaa")
    set.foreach((item: String) => println(item))

    var set2:mutable.Set[String] = mutable.Set[String]()
    set2.add("ttt")
    set2.add("####")
    set.foreach((item: String) => println(item))
  }

  def testMap(): Unit={
    var map: Map[String, Any] = Map[String, Any]()
    map += ("zzz" -> "000000")
    map += ("ttt" -> "11111")
    map.foreach(println)

    var map2: mutable.Map[String, Any] = mutable.HashMap[String, Any]()
    map2.put("aaa", "1111111111")
    map2.put("bbb", "2222222222")

    println(map2)
    map2.remove("aaa")
    println(map2)
  }
}

  

2. 流程控制語句

2.1 if/else

2.2 while/for

I. Python

II.Java

III.Scala

2.4 switch(Java)與match(Scala)

I. Python

    使用if/else實現

II.Java

III.Scala

3. 面向物件

  1. 類是抽象的,具有相同屬性和方法(行為)的集合
  2. 物件是具體的,具有某些屬性和方法(行為)
  3. 建立的物件的過程,叫例項化

3.1 類的初始化或類的建構函式

I. Python

II.Java

III.Scala

3.2類的訪問控制

  主要涉及public、protect、privite在父類和子類中的訪問範圍

    Public: 所有類都可見;三種語言概念一致

    Protect: pythonscala當前類及子類都可以訪問,java是當前類及子類都可以訪問,同時所在的同名的包中的類也可以訪問

    Privite: 僅限當前類,子類不可訪問,且不可以被重寫;三種語言概念一致

  I. Python

    Public:變數不是___開頭

    Protect:_ 單下劃線表示例如: _instance

    Privite:__雙下劃線表示例如:__instance

  II.Java

    略

  III.Scala

    略

3.3類的屬性與方法

I. Python

    有靜態屬性/方法,例項(動態)屬性/方法,類屬性/方法, 都可以被重寫

II.Java

    有靜態屬性/方法,例項(動態)屬性/方法

      java 中類屬性需要先定義,才能在具體函式中使用!!!; interface 中一般不定義屬性,更多的是介面函式,僅有方法名

    靜態屬性/方法不能被直接重寫,例項屬性/方法需要在建構函式中才能重寫

III.Scala

    沒有靜態屬性/方法,動態屬性/方法的概念

    但是有例項屬性/方法(相當於例項屬性/方法) 和 物件屬性/方法(相當於靜態屬性/方法),且都可以被重寫

3.4介面

I. Python

    通過定義類實現,方法體可有可無

II.Java

    通過interface定義實現,且無方法體,一般僅定義方法,因為介面中定義的屬性後不能被重寫

III.Scala

    通過trait定義實現,方法體可有可無

3.5繼承

  三者概念基本一致:

    1).繼承了父類的基本屬性和方法
    2).可以繼續實現自己的屬性和方法
    3).方法重寫:同名函式重寫,用另一種實現方案實現父類的方法

  I. Python

    有單繼承、多重繼承、多層繼承,都是通過class類本身定義

  II.Java

    有單繼承、多層繼承,通過class類本身定義

    但多重繼承是通過繼承多個介面即多個interface

  III.Scala

    同Java概念

3.6重寫與過載

  重寫:子類繼承父類後對父類的屬性或方法進行重寫,

    同時基類的私有方法能被子類重寫

  過載:同一個類中,方法名相同,但是引數不一樣(引數型別、數量)

I. Python

    僅重寫,沒有過載

II.Java

    靜態欄位不能被重寫,例項方法僅在建構函式中才能被重寫

III.Scala

    必須使用override修飾

3.7多型

  多型:

    目的是為了讓程式碼更加,降低耦合

    有繼承或實現特質(介面)

    父類引用指向子類物件或介面指向實現類

    方法需要重寫

  三者概念一致,

I. Python

II.Java

III.Scala

下面給出三種不同語言對工廠類模式的實現,1)繼承 2)屬性、方法是否可被重寫

Python工廠類實現

# coding=utf-8
import re


class BaseSite:

    url_patterns = []

    def __init__(self):
        super(BaseSite, self).__init__()

    def process(self, url, html):
        params = {
            'url': url,
            'html': html,
            'params': ''
        }
        return params


class Douban(BaseSite):

    url_patterns = ['https://movie.douban.com']

    def __init__(self):
        super(BaseSite, self).__init__()

    def process(self, url, html):
        params = {
            'url': url,
            'html': html,
            'params': 'douban'
        }
        return params


class Tencent(BaseSite):

    url_patterns = ['https?://www.qq.com']

    def __init__(self):
        super(BaseSite, self).__init__()

    def process(self, url, html):
        params = {
            'url': url,
            'html': html,
            'params': 'qq'
        }
        return params


class Factory:

    def __init__(self):
        self.site_list = []

    def init_factory(self):
        self.site_list.append(Douban())
        self.site_list.append(Tencent())

    def get_site(self, url):
        for site in self.site_list:
            for pattern in site.url_patterns:
                if re.search(pattern, url):
                    return site
        return BaseSite()


if __name__ == '__main__':
    factory = Factory()
    factory.init_factory()
    url = 'https://www.qq.com'
    html = '<html></html>'
    site = factory.get_site(url)
    params = site.process(url, html)
    print(params)

  

Java工廠類實現

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.*;

class Site {
    //    靜態屬性/方法不能被直接重寫,例項屬性/方法需要在建構函式中才能操作(近似重寫)
    List<String> urlPatterns = new ArrayList<String>();
//    初始化時,不要設定值,否則會被繼承到子類
//    public Site() {
//        this.urlPatterns.add("https?://www.common.com");
//    }

    public Map<String, Object> process(String url, String html) {
        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("url", url);
//        map.put("html", html);
        return map;
    }
}

class Baidu extends Site {

    //    靜態屬性/方法不能被直接重寫,例項屬性/方法需要在建構函式中才能操作(近似重寫)
    public Baidu() {
        this.urlPatterns.add(".*baidu.*");
    }
    public Map<String, Object> process(String url, String html) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", url);
        map.put("html", html);
        map.put("params", "baidu");
        return map;
    }
}

class Tencent extends Site {

    //    靜態屬性/方法不能被直接重寫,例項屬性/方法需要在建構函式中才能操作(近似重寫)
    public Tencent() {
        this.urlPatterns.add(".*qq.*");

    }
    public Map<String, Object> process(String url, String html) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", url);
        map.put("html", html);
        map.put("params", "qq");
        return map;
    }
}


class SiteFactory {
    List<Site> siteList = new ArrayList<Site>();

    public void initFactory() {
        this.siteList.add(new Baidu());
        this.siteList.add(new Tencent());

    }
    public Site getSite(String url) {
        Site tempSite = new Site();
        for(Site site: this.siteList) {
            for(String urlPattern: site.urlPatterns) {
                if(Pattern.matches(urlPattern, url)) {
                    return site;
                }
            }
        }
        return tempSite;
    }
}

public class Factory {
    public static void main(String[] args) {
        SiteFactory siteFactory = new SiteFactory();
        siteFactory.initFactory();
        String url = "https://www.baidu.com";
        Site site = siteFactory.getSite(url);
        System.out.println(site);
        Map<String, Object> map = site.process(url, "<html></html>");
        for(Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
    }

    public void test() {
        Site site = new Site();
        System.out.println(site.urlPatterns);
        Map<String, Object> map = site.process("https://www.baidu.com", "<html></html>");
        for(Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
    }
}

Scala工廠類實現

import scala.collection.mutable
import scala.util.matching.Regex

class BaseSite {
  //  屬性和方法都可以被重寫
  val urlPatterns = List[String]()

  def process(url: String, html: String): mutable.Map[String, Any]={
    var map = mutable.HashMap[String, Any]()
    map.put("url", url)
    map.put("html", html)
    map.put("params", "")
    map
  }
}

class BaseBaidu extends BaseSite {

  //  屬性和方法都可以被重寫
  override val urlPatterns = List[String](".*baidu.*")

  override def process(url: String, html: String): mutable.Map[String, Any] = {
    var map = super.process(url, html)
    map.put("params", "baidu")
    map
  }

}

class BaseFactoryList {

  var siteList = List[BaseSite]()
  def initFactory(): Unit= {
    siteList = siteList :+ new BaseBaidu()
  }

  def getSite(url: String): BaseSite = {
    var tempSite: BaseSite = new BaseSite()
    println(siteList)
    for (site: BaseSite <- siteList) {
      for (urlPattern: String <- site.urlPatterns) {
        val pattern = new Regex(urlPattern)
        tempSite = site
        if (pattern.matches(url)) {
          return site
        }
      }
    }
    tempSite
  }
}

object BaseFactory {

  def main(args: Array[String]): Unit = {
    val siteFactory: BaseFactoryList = new BaseFactoryList()
    siteFactory.initFactory()
    val url: String = "https://www.baidu.com"
    val site: BaseSite = siteFactory.getSite(url)
    val map = site.process(url, "<html></html>")
    map.foreach(println)
  }
//  缺少對各種資料結構的操作
}

4.其他模組封裝

4.1 時間處理封裝

package com.jsw.kg;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

public class TimeUtil {

    public static String UniformFormat = "yyyy-MM-dd HH:mm:SS";

    public static String timeFormat(Date date, String format) {
        DateFormat fm = new SimpleDateFormat(format);
        return fm.format(date);
    }

    public static String timeFormat(Date date) {
        return TimeUtil.timeFormat(date, UniformFormat);
    }

    public static String timeFormat() {
        return TimeUtil.timeFormat(new Date(), UniformFormat);
    }

    public static String timeFormat(Calendar calendar, String format) {
        Date date = calendarToDate(calendar);
        return TimeUtil.timeFormat(date, format);
    }

    public static String timeFormat(Calendar calendar) {
        return TimeUtil.timeFormat(calendar, UniformFormat);
    }

    /**
     * 時間轉換: 字串轉Date時間, 然後再轉其他時間字串
     */
    public static String timeFormat(String source, String sourceFormat, String format) {
        Date date = timeStringToDate(source, sourceFormat);
        return timeFormat(date, format);
    }

    /**
     * 時間轉換: 字串轉Date時間, 然後再轉預設通用時間字串
     */
    public static String timeFormat(String source, String sourceFormat) {
        return timeFormat(source, sourceFormat, UniformFormat);
    }

    /**
     * 時間轉換: 字串轉Date時間
     */
    public static Date timeStringToDate(String source, String sourceFormat) {
        DateFormat fm = new SimpleDateFormat(sourceFormat);
        Date date = null;
        try {
            date = fm.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Calendar dateToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public static Date calendarToDate(Calendar calendar) {
        Date date = calendar.getTime();
        return date;
    }

    public static long timeStamp(Date date) {
        return date.getTime();
    }

    public static long timeStamp(Calendar calendar) {
        //    return calendar.getTimeInMillis();
        return timeStamp(calendarToDate(calendar));
    }

    public static long timeStamp() {
        return timeStamp(new Date());
    }

    public static Date timeStampToDate(long time) {
        return new Date(time);
    }

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(timeFormat(date));
        System.out.println(timeStamp(date));
        System.out.println(timeStamp(timeStringToDate("2005-06-09", "yyyy-MM-dd")));

        System.out.println("###############");
        System.out.println(new Date().getTime());

        System.out.println(timeStampToDate(1386665666777L));
    }

}

4.2 正則封裝

scala程式碼

package com.jsw.kg

import scala.util.matching.Regex


object ScalaRegUtil {

    def search(pattern: String, string: String): Boolean={
        val r:Regex = new Regex(pattern)
        r.pattern.matcher(string).matches
    }

    def findAll(pattern: String, string: String): List[String]={
        val r:Regex = new Regex(pattern)
        var list = List[String]()
        if(r.pattern.matcher(string).matches) {
            val m = r.findAllIn(string)
            while(m.hasNext) {
                list = list :+ m.next()
            }
        }
        list
    }

    def replaceAll(string: String, pattern: String, replace: String): String = {
        val r:Regex = new Regex(pattern)
        r.replaceAllIn(string, replace)
    }

    def main(args: Array[String]): Unit = {
        val s = ScalaRegUtil.search("(abc).*", "abcdef")
        println(s)
        val s1 = ScalaRegUtil.replaceAll("abcdef", "(abc).*", "aaa")
        println(s1)
        val s2 = ScalaRegUtil.findAll("(abc).*", "abcdef")
        println(s2)
    }
}

Java程式碼

package com.jsw.kg;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaRegUtil {

    public static Matcher getMatcher(String pattern, String string) {
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(string);
        return m;
    }

    public static Boolean search(String pattern, String string) {
        return JavaRegUtil.getMatcher(pattern, string).matches();
    }

    public static List<String> findAll(String pattern, String string) {
        List<String> items = new ArrayList<String>();
        Matcher m = JavaRegUtil.getMatcher(pattern, string);
        if(m.matches()) {
            int count = m.groupCount();
            for(int i=1; i<=count; i++) {
                items.add(m.group(i));
            }
        }
        return items;
    }

    public static String replaceAll(String string, String pattern, String replace) {
        Matcher m = JavaRegUtil.getMatcher(pattern, string);
        if(m.matches()) {
            return m.replaceAll(replace);
        }
        return "";
    }

    public static void main(String[] args) {
        String line = "This order was placed for QT3000! OK?";
        String pattern = ".*(order.*placed).*";
        System.out.println(JavaRegUtil.search(pattern, line));
        System.out.println(JavaRegUtil.findAll(pattern, line));
    }

}

4.3 檔案處理封裝

scala程式碼

package com.jsw.kg;

import java.io.{BufferedWriter, File, FileWriter}

import scala.io.Source

object ScalaFileUtil{

    def readFile(path: String): Iterator[String]={
        val f = Source.fromFile(path)
        for (line: String <- f.getLines()) yield line
    }

    def wrieFile(path: String, lines: List[String], append: Boolean=false): Unit = {
        val writer = new BufferedWriter(new FileWriter(path, append))
        writer.write(lines.mkString("\n") + "\n")
        writer.close()
    }

    def getFileListObj(dir: File): Array[File] = {
        val fp = dir.listFiles
        val d = fp.filter(_.isDirectory)
        val f = fp.filter(_.isFile)
        f ++ d.flatMap(getFileListObj(_))
    }

    def getFileList(dir: String): List[String]={
        getFileListObj(new File(dir)).map(_.getPath).toList
    }

    def remove(path: String): Boolean={
        return JavaFileUtil.remove(path)
    }

    def main(args: Array[String]): Unit = {
        val path = "E:\\LocalCode\\allcode"
        getFileList(path).foreach(println)
//        writeFile(path, List("aaa", "bbb", "ccc"))
//        val lines = readFile(path)
//        lines.foreach(println)
    }
}

Java程式碼

package com.jsw.kg;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class JavaFileUtil {

    public static List<String> readFile(String path) throws IOException {
        List<String> lines = new ArrayList<String>();
        if(!exists(path)) {
            return lines;
        }
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line = reader.readLine();
        while (line != null) {
            line = reader.readLine();
            lines.add(line);
        }
        reader.close();
        return lines;
    }

    public static void writeFile(String path, List<String> lines) throws IOException {
        if(!exists(path)) {
            return;
        }
        BufferedWriter writer = new BufferedWriter(new FileWriter(path));
        for (String line: lines){
            writer.write(line);
        }
        writer.close();
    }

    public static Boolean exists(String path) {
        File file = new File(path);        //獲取其file物件
        return file.exists();
    }

    public static List<String> getFileList(String path, List<String> files) {
        if (!exists(path)) {
            return files;
        }
        File file = new File(path);        //獲取其file物件
        File[] fs = file.listFiles();    //遍歷path下的檔案和目錄,放在File陣列中
        for(File f: fs) {                //遍歷File[]陣列
            if(f.isDirectory())
                getFileList(f.getPath(), files);
            else {
                files.add(f.getPath());
            }
        }
        return files;
    }

    public static void mkdir(String path) {
        File file = new File(path);
        // 現在建立目錄
        file.mkdirs();
    }

    public static boolean remove(String path) {
        if(!exists(path)) {
            return false;
        }
        File file = new File(path);
        // 現在建立目錄
        if(file.isFile()) {
            System.out.println("delete file: " + file.getPath());
            return file.delete();
        } else {
            for(File f: file.listFiles()) {
                remove(f.getPath());
            }
            System.out.println("delete dir: " + file.getPath());
            return file.delete();
        }
    }

    public static void main(String[] args) {
        String path = "E:\\Program Files\\eclipse\\kg\\src";
//        JavaFileUtil.remove(path);
        List<String> files = new ArrayList<String>();
        JavaFileUtil.getFileList(path, files);
        for (String file: files) {
            System.out.println(file);
        }
    }
}

注意事項:

1)關於建立maven時可以指定架構:

目錄級別:project--->package--->class(object) 使用maven時,可以統一基本程式碼框架

2)關於maven打包指定mainClass, pom.xml中新增如下配置:

  <build>
        <plugins>
            <plugin>
                      <groupId>org.apache.maven.plugins</groupId>
                      <artifactId>maven-jar-plugin</artifactId>
                      <version>3.0.2</version>
                      <configuration>
                          <archive>
                              <manifest>
                                  <addClasspath>true</addClasspath>
                                  <!-- 此處為程式主入口-->
                                  <mainClass>com.jsw.kg.App</mainClass>
                              </manifest>
                          </archive>
                      </configuration>
            </plugin>
        </plugins>
    </build>

3)IDEA打包設定如下:

本地實現具體如下:(分開打包)

正常執行如下: