Java版WordCount、伴生对象、函数的定义

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Demo06WordCountJava {
    public static void main(String[] args) throws IOException {
        //用Java代码是实现WordCount
        //读文件
        BufferedReader br = new BufferedReader(new FileReader("Scala/data/words.txt"));
        String line;
        //使用HashMap进行存储
        HashMap<String, Integer> wordCntMap = new HashMap<>();
        while ((line = br.readLine()) != null) {
            //处理每一行数据
            //按照分隔符切分
            String[] words = line.split(",");
            for (String word : words) {
                /**
                 * 判断每个单词word 在不在wordCntMap的key中
                 * 如果在 则value+1
                 * 如果不在 第一次取到 则value置为1
                 */
                if(wordCntMap.containsKey(word)){
                    Integer value = wordCntMap.get(word);
                    wordCntMap.put(word,value+1);
                }else{
                    wordCntMap.put(word,1);
                }
            }
        }
        //将单词数量做一个打印
        for (Map.Entry<String, Integer> wordCnt : wordCntMap.entrySet()) {
            System.out.println(wordCnt.getKey()+":"+wordCnt.getValue());
        }
    }
}

java:20
spark:10
hadoop:10

object Demo07ScalaApply {
  def main(args: Array[String]): Unit = {
    //创建一辆汽车
    val car1: Car = new Car("本田", "黑色")
    println(car1._bread)

    val car2: Car = Car.apply("本田", "白色")
    println(car2._bread)

    val car3: Car = Car("马自达", "白色")
    println(car3._bread)
  }
}

class Car(brand:String,color:String){
  val _bread:String=brand
  val _color:String=color
}

//伴生对象
object Car{
  def apply(bread:String,color:String): Car = new Car(bread, color)
}

本田
本田
马自达

object Demo08Func1 {
  /**
   * 函数的定义
   * 函数可以定义在 类中、object中、方法中
   */
  def main(args: Array[String]): Unit = {
    def func1(): Unit ={
      println("在函数中定义函数")
    }
    func1()

    println(func2("100","200"))

    println(func3("100","200"))
  }

  /**
   *def 关键字 表示声明一个函数
   * func2 方法名
   * str1:String,str2:String 两个参数
   * str1、str2参数名 String为参数类型 多个参数之间用逗号分隔
   * Int 返回值类型
   * (......} 方法体
   * 返回值通过return返回
   */
  def func2(str1:String,str2:String): String ={
    return str1+str2
  }

  def func3(str1:String,str2:String): Int ={
    return str1.toInt+str2.toInt
  }
}

在函数中定义函数
100200
300

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值